appkit  1.5.1
RoadNarrows Robotics Application Kit
rnr::cmd::CommandLine Class Reference

CommandLine class. More...

#include <CommandLine.h>

Public Member Functions

 CommandLine (const std::string strName="cl", const std::string strPrompt="> ", bool bUseRlLib=true, bool bIgnoreCase=false)
 Default initialization constructor. More...
 
virtual ~CommandLine ()
 Destructor.
 
bool isDefined () const
 
bool ok () const
 Test if command-line interface is ok to continue. More...
 
void quit ()
 Mark command-line interface to quit.
 
bool getBtEnable () const
 Test if backtracing is enabled. More...
 
void setBtEnable (bool bEnable)
 Enable/disable backtracing. More...
 
virtual int addCommand (const CmdDesc &desc)
 Add a command to the command line interface. More...
 
virtual int addCommand (const CmdDesc &desc, CmdExec1Func fnExec)
 Add a command to the command line interface. More...
 
virtual int addCommand (const CmdDesc &desc, CmdExec2Func fnExec)
 Add a command to the command line interface. More...
 
virtual int addCommand (const CmdDesc &desc, CmdExec3Func fnExec)
 Add a command to the command line interface. More...
 
virtual int addCommand (const std::string strSyntax)
 Add a command to the command line interface. More...
 
virtual int addCommand (const std::string strSyntax, CmdExec1Func fnExec)
 Add a command to the command line interface. More...
 
virtual int addCommand (const std::string strSyntax, CmdExec2Func fnExec)
 Add a command to the command line interface. More...
 
virtual int addCommand (const std::string strSyntax, CmdExec3Func fnExec)
 Add a command to the command line interface. More...
 
virtual int removeCommand (const int uid)
 Remove command from command line interface. More...
 
virtual int removeCommand (const std::string &strName)
 Remove command from command line interface. More...
 
virtual int removeAllCommands ()
 Remove all commands from command line interface. More...
 
virtual int compile ()
 Compile all added commands. More...
 
int addDataSection (const std::string &ns, void *pData, DataSect::DeallocFunc fn=NULL)
 Add a data section to the command-line interface. More...
 
int removeDataSection (const std::string &ns)
 Remove a data section from the command-line interface. More...
 
void * getDataSection (const std::string &ns)
 Get the section data under the specified namespace. More...
 
bool isReservedDataSection (const std::string &ns) const
 Test if the namespace is a command-line interface reserved name. More...
 
virtual int readCommand (int &uid, int &iform, str::StringVec &argv)
 Read an input line from stdin and match to the best compiled command. More...
 
virtual int readCommand (CmdExtArgVec &argv)
 Read an input line from stdin and match to the best compiled command. More...
 
virtual int readCommand (FILE *fp, int &uid, int &iform, str::StringVec &argv)
 Read an input line from file fp and match to the best compiled command. More...
 
virtual int readCommand (FILE *fp, CmdExtArgVec &argv)
 Read an input line from file fp and match to the best compiled command. More...
 
bool kbhit ()
 
bool kbhit (FILE *fp)
 
virtual int execute (const str::StringVec &argv)
 Execute a comamnd with the given arguments. More...
 
virtual int execute (const CmdExtArgVec &argv)
 Execute a comamnd with the given arguments. More...
 
virtual void addToHistory (const str::StringVec &argv)
 Add command to history. More...
 
virtual void addToHistory (const CmdExtArgVec &argv)
 Add command to history. More...
 
void pushPrompt (const std::string &strPrompt)
 Push prompt string onto stack of prompts. More...
 
void popPrompt ()
 Pop prompt string from stack of prompts. More...
 
const std::string & getPrompt () const
 Get the current prompt string. More...
 
size_t getLineNum () const
 Get the line number of the last read line. More...
 
void setLineNum (const size_t uLineNum)
 Set the current line number. More...
 
void resetLineNum ()
 Reset the line number to zero.
 
int numOfArgs (int uid, int iform) const
 Get the total number of arguments. More...
 
int numOfArgs (const CmdExtArg &arg) const
 Get the total number of arguments of matched command. More...
 
int numOfRequiredArgs (int uid, int iform) const
 Get the total number of required arguments. More...
 
int numOfRequiredArgs (const CmdExtArg &arg) const
 Get the total number of required arguments of matched command. More...
 
int numOfOptionalArgs (int uid, int iform) const
 Get the total number of optional arguments. More...
 
int numOfOptionalArgs (const CmdExtArg &arg) const
 Get the total number of arguments of matched command. More...
 
const std::string & getArgName (const CmdExtArg &arg) const
 Get the argument name. More...
 
CmdArgDef::ArgType getArgDefType (const CmdExtArg &arg) const
 Get the argument type. More...
 
virtual ssize_t tokenizeInput (const std::string &strInput, TokenVec &tokens)
 Lexically analyze input string to generate a series of tokens. More...
 
virtual ssize_t tokenizeInput (const std::string &strInput, str::StringVec &tokens)
 Lexically analyze input string to generate a series of string tokens. More...
 
const std::string & getName () const
 Get command line interface's name. More...
 
bool hasCmd (const int uid) const
 Test if command exists. More...
 
bool hasCmd (const std::string &strName) const
 Test if command exists. More...
 
const CmdDefat (const int uid) const
 Get the command definition with the unique id. More...
 
const CmdDefat (const std::string &strName) const
 Get command definition with the argv0 name. More...
 
const CmdDefoperator[] (const int uid) const
 Index operator. More...
 
const CmdDefoperator[] (const std::string &strName) const
 Index operator. More...
 
int numOfCmds () const
 Get the total number of added commands. More...
 
CmdDefCIter begin () const
 Return a constant iterator pointing to the first element of the list of command definitions. More...
 
CmdDefCIter end () const
 Return a constant iterator referring to the past-the-end element of the list of command definitions. More...
 
const std::string & getErrorStr () const
 Get the most recent error. More...
 
std::ostream & backtrace (std::ostream &os, const bool bAll=false) const
 Insert trace and error log backtrace into output stream. More...
 

Static Public Member Functions

static std::string c14n (const TokenVec &tokens)
 Canonicalization of a string. More...
 

Protected Member Functions

CmdDefcmdAt (const int uid)
 Get modifiable command definition with the given unique id. More...
 
CmdDefcmdAt (const std::string &strName)
 Get modifiable command definition with the given argv0 name. More...
 
virtual ssize_t tokenizeSyntax (const std::string &strSyntax, TokenVec &tokens)
 Lexically analyze extened usage syntax string to generate a series of tokens. More...
 
virtual ssize_t lexSyntaxWord (const std::string &strSyntax, ssize_t cursor, TokenVec &tokens)
 Syntax word lexical analyzer. More...
 
virtual ssize_t lexSyntaxParenExpr (const std::string &strSyntax, ssize_t cursor, TokenVec &tokens)
 Syntax parenthetical expression lexical analyzer. More...
 
virtual ssize_t lexWord (const std::string &strInput, ssize_t cursor, TokenVec &tokens)
 Word lexical analyzer. More...
 
virtual ssize_t lexQuotedString (const std::string &strInput, ssize_t cursor, TokenVec &tokens)
 Quoted string lexical analyzer. More...
 
virtual void logLexToken (const std::string &strSource, const size_t start, const ssize_t cursor, TokenVec &tokens, const bool bLoc=false)
 Log lexigraphical token. More...
 
void pushToken (const std::string &strSource, const size_t start, const ssize_t cursor, TokenVec &tokens)
 Push token to the end of the generated tokens. More...
 
virtual int compile (CmdDef &cmddef)
 Compile a command. More...
 
int finalize ()
 Finalize command compilation. More...
 
virtual int parseSyntax (CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens)
 Parse command syntax. More...
 
bool parseArgv0 (CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos)
 Parse argument 0 (command name) syntax. More...
 
bool parseRequiredArgList (CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos)
 Parse required argument list syntax. More...
 
bool parseOptionalArgList (CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos)
 Parse optional argument list syntax. More...
 
bool parseArg (CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos)
 Parse argument syntax. More...
 
bool parseXorListArg (CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos)
 Parse mutually exclusive argument values syntax. More...
 
bool parseVariableArg (CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos)
 Parse variable argument syntax. More...
 
bool parseLiteralArg (CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos)
 Parse literal, fixed-valued argument syntax. More...
 
bool parseXorList (CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos, str::StringVec &literals)
 Parse mutually exclusive list. More...
 
bool parseIdentifier (CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos, std::string &strIdent)
 Parse identifier. More...
 
bool parseVarMod (CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos, CmdArgDef::ArgType &eType, CmdArgDef::RangeVec &ranges, RegEx &re)
 Parse variable modifier. More...
 
bool parseVarType (CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos, CmdArgDef::ArgType &eType)
 Parse variable type. More...
 
bool parseVarRangeExpr (CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos, CmdArgDef::RangeVec &ranges)
 Parse variable range expression. More...
 
bool parseVarRegExpr (CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos, RegEx &re)
 Parse variable regular expression. More...
 
bool parseLiteralValue (CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos, std::string &strValue)
 Parse literal value. More...
 
bool tokEq (const std::string strCmp, const TokenVec &tokens, size_t &pos)
 Test if token at position is equal to string. More...
 
bool peekEq (const std::string strCmp, const Token &token) const
 Peek if token is equal to string. More...
 
bool tokIdentifier (const TokenVec &tokens, size_t &pos)
 Test if string has valid identifier syntax. More...
 
int processInput (const std::string &strLine, CmdExtArgVec &argv)
 Process a line of input. More...
 
int match (const TokenVec &tokens, CmdExtArgVec &argv)
 Match the input tokens to the compiled commands to find the best fit. More...
 
int matchCommand (const CmdDef &cmddef, const TokenVec &tokens, CmdExtArgVec &argv, double &fFitness)
 Match best command form against input line argument list. More...
 
int matchCommandForm (const CmdFormDef &form, const TokenVec &tokens, CmdExtArgVec &argv, double &fFitness)
 Match command form against input line argument list. More...
 
int checkReadResult ()
 Check read input result. More...
 
void toVec (const CmdExtArgVec &v1, str::StringVec &v2)
 Convert extended argument vector to string argument vector. More...
 
virtual int rlBuildReadLineGenerator ()
 Perform any necessary pre-processing to prepare for command line TAB completion. More...
 
virtual const std::string rlGenerator (const std::string &strText, int nIndex, const std::string &strContext, int nStart, int nEnd, unsigned &uFlags)
 TAB completion generator. More...
 
void rlArgDefs (const std::string &strSubtext, std::vector< CmdArgDef * > &argdefs)
 Build list of all command argument definitions that match completed subtext. More...
 
void rlTabList (const std::string &strText, std::vector< CmdArgDef * > &argdefs, str::StringVec &tabList, unsigned &uFlags)
 Build TAB completion list and set appropriate readline modifiers. More...
 
bool rlPartialMatch (const std::string &strText, const std::string strLiteral, const size_t uLen)
 Match partial text agains literal string. More...
 

Static Protected Member Functions

static const std::string rlGeneratorWrapper (void *pAppArg, const std::string &strText, int nIndex, const std::string &strContext, int nStart, int nEnd, unsigned &uFlags)
 Static TAB completion generator wrapper. More...
 

Protected Attributes

std::string m_strName
 name of this command line
 
bool m_bIgnoreCase
 do [not] ignore case on commands
 
int m_nUidCnt
 unique id counter
 
bool m_bIsCompiled
 has [not] been successfully compiled
 
CmdDefMap m_cmdDefs
 map of added command definitions
 
CmdExecMap m_cmdExecs
 map of added command executions
 
PromptStack m_prompts
 stack of prompt strings
 
ReadLine m_readline
 readline interface
 
LogBook m_log
 trace and error log
 
DataSectMap m_dataSects
 data sections
 

Friends

std::ostream & operator<< (std::ostream &os, const CommandLine &cl)
 Insert object into output stream. More...
 

Detailed Description

CommandLine class.

Definition at line 444 of file CommandLine.h.

Constructor & Destructor Documentation

CommandLine::CommandLine ( const std::string  strName = "cl",
const std::string  strPrompt = "> ",
bool  bUseRlLib = true,
bool  bIgnoreCase = false 
)

Default initialization constructor.

Parameters
strNameName of command set and entry into readline's conditional parsing of the ~/.inputrc file.
strPromptCommand line primary prompt string. Prompting occurs only in interactive mode.
bUseRlLibUse the readline library. Note that readline must be available and in interactive mode. Otherwise a simple command-line interface will be used.
bIgnoreCaseIgnore case on comands and arguments.

Definition at line 383 of file CommandLine.cxx.

References addDataSection(), rnr::cmd::DataSectNsCore, rnr::cmd::DataSectCore::dealloc(), m_bIsCompiled, m_nUidCnt, and pushPrompt().

386  :
387  m_strName(strName),
388  m_bIgnoreCase(bIgnoreCase),
389  m_readline(strName, strPrompt, bUseRlLib),
390  m_log("Command Line Log", 50)
391 {
392  m_nUidCnt = 0;
393  m_bIsCompiled = false;
394 
396 
397  pushPrompt(strPrompt);
398 }
std::string m_strName
name of this command line
Definition: CommandLine.h:1187
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
ReadLine m_readline
readline interface
Definition: CommandLine.h:1194
bool m_bIsCompiled
has [not] been successfully compiled
Definition: CommandLine.h:1190
static void dealloc(void *p)
Deallocate (delete) allocated (new) core data section.
Definition: CmdCore.cxx:85
const char *const DataSectNsCore
Reserved command line data section namespaces.
Definition: CmdCore.h:141
void pushPrompt(const std::string &strPrompt)
Push prompt string onto stack of prompts.
int addDataSection(const std::string &ns, void *pData, DataSect::DeallocFunc fn=NULL)
Add a data section to the command-line interface.
bool m_bIgnoreCase
do [not] ignore case on commands
Definition: CommandLine.h:1188
int m_nUidCnt
unique id counter
Definition: CommandLine.h:1189
Core data section type.
Definition: CmdCore.h:148

Member Function Documentation

int CommandLine::addCommand ( const CmdDesc desc)
virtual

Add a command to the command line interface.

The command syntax may specify multiple command forms, each separated by a newline '\n' character. The command named in each form must be the identical.

This is a light-weight function. A call to compile() is necessary to finalized command syntax processing.

Parameters
descCommand description (see CmdDesc).
strSyntaxOne or more extended usage syntax separated by newline characters.
fnExecCommand execution function of variant 1, 2, or 3.
Returns
On success, returns command's assigned unique id. Otherwise NoUid is returned.

Definition at line 414 of file CommandLine.cxx.

References rnr::eoe(), getErrorStr(), LOGERROR_STREAM, rnr::cmd::CmdDesc::longdesc, m_cmdDefs, m_log, rnr::cmd::NoUid, rnr::cmd::CmdDesc::synopsis, and rnr::cmd::CmdDesc::syntax.

Referenced by addCommand(), rnr::cmd::addons::execBtEnable(), rnr::cmd::addons::execQuit(), execTAdd(), loadCommands(), and rnr::cmd::addons::printCmdHelp().

415 {
416  int uid;
417 
418  // command syntax must be defined
419  if( desc.syntax.empty() )
420  {
421  m_log << "No syntax forms specified." << eoe;
423  return NoUid;
424  }
425 
426  // add command
427  if( (uid = addCommand(desc.syntax)) != NoUid )
428  {
429  m_cmdDefs[uid].addHelp(desc.synopsis, desc.longdesc);
430  }
431 
432  return uid;
433 }
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
std::string synopsis
short command synopsis
Definition: CmdCore.h:89
std::string longdesc
long command description
Definition: CmdCore.h:90
const int NoUid
Special values.
Definition: CmdCore.h:116
virtual int addCommand(const CmdDesc &desc)
Add a command to the command line interface.
LogBook & eoe(LogBook &log)
LogBook end-of-entry stream manipulator.
Definition: LogBook.cxx:926
#define LOGERROR_STREAM(args)
Error stream logging.
Definition: LogStream.h:167
std::string syntax
parsable command extended usage syntax
Definition: CmdCore.h:88
const std::string & getErrorStr() const
Get the most recent error.
CmdDefMap m_cmdDefs
map of added command definitions
Definition: CommandLine.h:1191
int CommandLine::addCommand ( const CmdDesc desc,
CmdExec1Func  fnExec 
)
virtual

Add a command to the command line interface.

The command syntax may specify multiple command forms, each separated by a newline '\n' character. The command named in each form must be the identical.

This is a light-weight function. A call to compile() is necessary to finalized command syntax processing.

Parameters
descCommand description (see CmdDesc).
strSyntaxOne or more extended usage syntax separated by newline characters.
fnExecCommand execution function of variant 1, 2, or 3.
Returns
On success, returns command's assigned unique id. Otherwise NoUid is returned.

Definition at line 435 of file CommandLine.cxx.

References addCommand(), m_cmdExecs, and rnr::cmd::NoUid.

436 {
437  int uid;
438 
439  // add command
440  if( (uid = addCommand(desc)) != NoUid )
441  {
442  m_cmdExecs[uid] = CmdExec(uid, fnExec);
443  }
444 
445  return uid;
446 }
const int NoUid
Special values.
Definition: CmdCore.h:116
CmdExecMap m_cmdExecs
map of added command executions
Definition: CommandLine.h:1192
virtual int addCommand(const CmdDesc &desc)
Add a command to the command line interface.
Helper class to hold a command line execution function.
Definition: CommandLine.h:164
int CommandLine::addCommand ( const CmdDesc desc,
CmdExec2Func  fnExec 
)
virtual

Add a command to the command line interface.

The command syntax may specify multiple command forms, each separated by a newline '\n' character. The command named in each form must be the identical.

This is a light-weight function. A call to compile() is necessary to finalized command syntax processing.

Parameters
descCommand description (see CmdDesc).
strSyntaxOne or more extended usage syntax separated by newline characters.
fnExecCommand execution function of variant 1, 2, or 3.
Returns
On success, returns command's assigned unique id. Otherwise NoUid is returned.

Definition at line 448 of file CommandLine.cxx.

References addCommand(), m_cmdExecs, and rnr::cmd::NoUid.

449 {
450  int uid;
451 
452  // add command
453  if( (uid = addCommand(desc)) != NoUid )
454  {
455  m_cmdExecs[uid] = CmdExec(uid, fnExec);
456  }
457 
458  return uid;
459 }
const int NoUid
Special values.
Definition: CmdCore.h:116
CmdExecMap m_cmdExecs
map of added command executions
Definition: CommandLine.h:1192
virtual int addCommand(const CmdDesc &desc)
Add a command to the command line interface.
Helper class to hold a command line execution function.
Definition: CommandLine.h:164
int CommandLine::addCommand ( const CmdDesc desc,
CmdExec3Func  fnExec 
)
virtual

Add a command to the command line interface.

The command syntax may specify multiple command forms, each separated by a newline '\n' character. The command named in each form must be the identical.

This is a light-weight function. A call to compile() is necessary to finalized command syntax processing.

Parameters
descCommand description (see CmdDesc).
strSyntaxOne or more extended usage syntax separated by newline characters.
fnExecCommand execution function of variant 1, 2, or 3.
Returns
On success, returns command's assigned unique id. Otherwise NoUid is returned.

Definition at line 461 of file CommandLine.cxx.

References addCommand(), cmdAt(), rnr::eoe(), getErrorStr(), rnr::cmd::CmdDef::getUid(), LOGERROR_STREAM, m_bIsCompiled, m_cmdDefs, m_cmdExecs, m_log, m_nUidCnt, rnr::cmd::CmdDef::m_strSyntax, rnr::cmd::NoUid, rnr::cmd::CmdDef::pushForm(), rnr::cmd::CmdDef::setUid(), and rnr::str::split().

462 {
463  int uid;
464 
465  // add command
466  if( (uid = addCommand(desc)) != NoUid )
467  {
468  m_cmdExecs[uid] = CmdExec(uid, fnExec);
469  }
470 
471  return uid;
472 }
const int NoUid
Special values.
Definition: CmdCore.h:116
CmdExecMap m_cmdExecs
map of added command executions
Definition: CommandLine.h:1192
virtual int addCommand(const CmdDesc &desc)
Add a command to the command line interface.
Helper class to hold a command line execution function.
Definition: CommandLine.h:164
virtual int rnr::cmd::CommandLine::addCommand ( const std::string  strSyntax)
virtual

Add a command to the command line interface.

The command syntax may specify multiple command forms, each separated by a newline '\n' character. The command named in each form must be the identical.

This is a light-weight function. A call to compile() is necessary to finalized command syntax processing.

Parameters
descCommand description (see CmdDesc).
strSyntaxOne or more extended usage syntax separated by newline characters.
fnExecCommand execution function of variant 1, 2, or 3.
Returns
On success, returns command's assigned unique id. Otherwise NoUid is returned.
virtual int rnr::cmd::CommandLine::addCommand ( const std::string  strSyntax,
CmdExec1Func  fnExec 
)
virtual

Add a command to the command line interface.

The command syntax may specify multiple command forms, each separated by a newline '\n' character. The command named in each form must be the identical.

This is a light-weight function. A call to compile() is necessary to finalized command syntax processing.

Parameters
descCommand description (see CmdDesc).
strSyntaxOne or more extended usage syntax separated by newline characters.
fnExecCommand execution function of variant 1, 2, or 3.
Returns
On success, returns command's assigned unique id. Otherwise NoUid is returned.
virtual int rnr::cmd::CommandLine::addCommand ( const std::string  strSyntax,
CmdExec2Func  fnExec 
)
virtual

Add a command to the command line interface.

The command syntax may specify multiple command forms, each separated by a newline '\n' character. The command named in each form must be the identical.

This is a light-weight function. A call to compile() is necessary to finalized command syntax processing.

Parameters
descCommand description (see CmdDesc).
strSyntaxOne or more extended usage syntax separated by newline characters.
fnExecCommand execution function of variant 1, 2, or 3.
Returns
On success, returns command's assigned unique id. Otherwise NoUid is returned.
virtual int rnr::cmd::CommandLine::addCommand ( const std::string  strSyntax,
CmdExec3Func  fnExec 
)
virtual

Add a command to the command line interface.

The command syntax may specify multiple command forms, each separated by a newline '\n' character. The command named in each form must be the identical.

This is a light-weight function. A call to compile() is necessary to finalized command syntax processing.

Parameters
descCommand description (see CmdDesc).
strSyntaxOne or more extended usage syntax separated by newline characters.
fnExecCommand execution function of variant 1, 2, or 3.
Returns
On success, returns command's assigned unique id. Otherwise NoUid is returned.
int CommandLine::addDataSection ( const std::string &  ns,
void *  pData,
DataSect::DeallocFunc  fn = NULL 
)

Add a data section to the command-line interface.

When the section is removed or the interface is deleted, the section data is automatically deleted if a deallocation function is specified. Otherwise, the user has responsibility to delete any data.

Parameters
nsNamespace of data section.
pDataPointer to data.
fnDeallocator function.
Returns
On success, AOk(0) is returned. On error, a CommandLine error code (< 0) is returned. See getErroStr() and backtrace() to retrieve or print error(s).

Definition at line 790 of file CommandLine.cxx.

References rnr::cmd::AOk, rnr::cmd::EBadVal, LOGERROR_STREAM, and m_dataSects.

Referenced by CommandLine().

793 {
794  DataSectIter pos = m_dataSects.find(ns);
795 
796  if( pos == m_dataSects.end() )
797  {
798  m_dataSects[ns] = DataSect(); // avoid double deletes
799  m_dataSects[ns].set(ns, pData, fn); // now assign
800  return AOk;
801  }
802  else
803  {
804  LOGERROR_STREAM("Data section '" << ns << "' already exist - cannot add.");
805  return EBadVal;
806  }
807 }
Command line interface data section class.
Definition: CommandLine.h:315
const int AOk
(0) A-Ok, no error, success, good
Definition: CmdCore.h:93
const int EBadVal
bad value
Definition: CmdCore.h:108
#define LOGERROR_STREAM(args)
Error stream logging.
Definition: LogStream.h:167
DataSectMap::iterator DataSectIter
iterator type
Definition: CommandLine.h:431
DataSectMap m_dataSects
data sections
Definition: CommandLine.h:1196
void CommandLine::addToHistory ( const str::StringVec argv)
virtual

Add command to history.

Simple string argument version.

Note
Only available if readline is available and enabled, and input is interactive.
Parameters
argvCommand in argv vector.

Definition at line 1039 of file CommandLine.cxx.

References rnr::str::c14n(), and m_readline.

Referenced by run().

1040 {
1041  m_readline.addToHistory(str::c14n(argv));
1042 }
ReadLine m_readline
readline interface
Definition: CommandLine.h:1194
std::string c14n(const std::string &str)
Simple canonicalization of a string.
void CommandLine::addToHistory ( const CmdExtArgVec argv)
virtual

Add command to history.

Extended argument version.

Note
Only available if readline is available and enabled, and input is interactive.
Parameters
argvCommand in argv vector.

Definition at line 1044 of file CommandLine.cxx.

References rnr::str::c14n(), m_readline, and toVec().

1045 {
1046  StringVec v;
1047 
1048  toVec(argv, v);
1049  m_readline.addToHistory(str::c14n(v));
1050 }
std::vector< std::string > StringVec
Useful types.
Definition: StringTheory.h:83
void toVec(const CmdExtArgVec &v1, str::StringVec &v2)
Convert extended argument vector to string argument vector.
ReadLine m_readline
readline interface
Definition: CommandLine.h:1194
std::string c14n(const std::string &str)
Simple canonicalization of a string.
const CmdDef & CommandLine::at ( const int  uid) const

Get the command definition with the unique id.

Parameters
uidCommand unique id.
Returns
Command definition reference.

Definition at line 1889 of file CommandLine.cxx.

References m_cmdDefs, and rnr::cmd::nocmddef.

Referenced by checkCmd(), rnr::cmd::addons::execHelp(), execTDump(), execTRemove(), getArgDefType(), getArgName(), hasCmd(), numOfArgs(), numOfOptionalArgs(), and numOfRequiredArgs().

1890 {
1891  CmdDefCIter pos;
1892 
1893  if( (pos = m_cmdDefs.find(uid)) != m_cmdDefs.end() )
1894  {
1895  return pos->second;
1896  }
1897  else
1898  {
1899  return nocmddef;
1900  }
1901 }
CmdDefMap::const_iterator CmdDefCIter
cmd const iter type
Definition: CommandLine.h:418
static CmdDef nocmddef
"no cmd def" command definition
CmdDefMap m_cmdDefs
map of added command definitions
Definition: CommandLine.h:1191
const CmdDef& rnr::cmd::CommandLine::at ( const std::string &  strName) const

Get command definition with the argv0 name.

Parameters
strNameCommand name.
Returns
Command definition reference.
ostream & CommandLine::backtrace ( std::ostream &  os,
const bool  bAll = false 
) const

Insert trace and error log backtrace into output stream.

Parameters
osOutput stream.
bAllIf true, backtrace all of log. Otherwise backtrace to last major execution mark.
Returns
Reference to output stream.

Definition at line 1952 of file CommandLine.cxx.

References rnr::cmd::isdquote(), lexQuotedString(), lexWord(), m_log, rnr::LogBook::NEWEST, rnr::LogBook::printLog(), rnr::LogBook::printToMark(), and tokenizeInput().

Referenced by execTBt(), loadCommands(), and readCommand().

1953 {
1954  if( bAll )
1955  {
1956  return m_log.printLog(os);
1957  }
1958  else
1959  {
1960  return m_log.printToMark(os, markExec, LogBook::NEWEST);
1961  }
1962 }
std::ostream & printToMark(std::ostream &os, const std::string strMark, int endpt) const
Print the log book entires between the bookmark and the specified end point to the output stream...
Definition: LogBook.cxx:646
std::ostream & printLog(std::ostream &os) const
Print the entire log book to the output stream.
Definition: LogBook.cxx:630
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
static const int NEWEST
newest, most recent entries
Definition: LogBook.h:92
CmdDefCIter rnr::cmd::CommandLine::begin ( ) const
inline

Return a constant iterator pointing to the first element of the list of command definitions.

Returns
Constant Iterator.

Definition at line 1119 of file CommandLine.h.

Referenced by rnr::cmd::addons::execHelp().

1120  {
1121  return m_cmdDefs.begin();
1122  }
CmdDefMap m_cmdDefs
map of added command definitions
Definition: CommandLine.h:1191
string CommandLine::c14n ( const TokenVec tokens)
static

Canonicalization of a string.

Note
The name c14n is an cute abbreviation where 14 represents the number of letters between the 'c' and 'n' in the word "canonicalization".
Parameters
tokensTokens to canonicalize.
Returns
Return string holding canonical form.

Definition at line 3174 of file CommandLine.cxx.

References rnr::io::deltaindent(), getPrompt(), rnr::cmd::ReadLine::haveRlLib(), rnr::io::indent(), m_bIgnoreCase, m_cmdDefs, m_cmdExecs, m_dataSects, m_readline, m_strName, numOfCmds(), operator<<(), rnr::str::prettify(), rnr::io::setindent(), and rnr::cmd::ReadLine::useRlLib().

Referenced by match().

3175 {
3176  stringstream ss;
3177  string sep;
3178 
3179  for(size_t i = 0; i < tokens.size(); ++i)
3180  {
3181  ss << sep << prettify(tokens[i].value());
3182 
3183  if( i == 0 )
3184  {
3185  sep = " ";
3186  }
3187  }
3188 
3189  return ss.str();
3190 }
std::string prettify(const std::string &str)
Prettify string.
int CommandLine::checkReadResult ( )
protected

Check read input result.

Returns
On success, AOk(0) is returned. On error, a CommandLine error code (< 0) is returned. See getErroStr() and backtrace() to retrieve or print error(s).

Definition at line 1506 of file CommandLine.cxx.

References rnr::cmd::AOk, rnr::cmd::EEoF, rnr::eoe(), rnr::cmd::ERead, rnr::cmd::ReadLine::getErrorStr(), rnr::cmd::ReadLine::isEoF(), rnr::cmd::ReadLine::isFError(), m_log, and m_readline.

Referenced by processInput().

1507 {
1508  // EOF
1509  if( m_readline.isEoF() )
1510  {
1511  m_log << "EOF" << eoe;
1512  return EEoF;
1513  }
1514 
1515  // file read error
1516  else if( m_readline.isFError() )
1517  {
1518  m_log << m_readline.getErrorStr() << eoe;
1519  return ERead;
1520  }
1521 
1522  // read successful
1523  else
1524  {
1525  return AOk;
1526  }
1527 }
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
ReadLine m_readline
readline interface
Definition: CommandLine.h:1194
LogBook & eoe(LogBook &log)
LogBook end-of-entry stream manipulator.
Definition: LogBook.cxx:926
const int ERead
read error
Definition: CmdCore.h:101
const int AOk
(0) A-Ok, no error, success, good
Definition: CmdCore.h:93
bool isFError() const
Test if the last read operation resulted in an I/O error condition.
Definition: ReadLine.h:483
bool isEoF() const
Test if the last read operation resulted in an end-of-file condition.
Definition: ReadLine.h:472
const int EEoF
end of file
Definition: CmdCore.h:100
const std::string & getErrorStr() const
Get the most recently set error string.
Definition: ReadLine.cxx:322
CmdDef & CommandLine::cmdAt ( const int  uid)
protected

Get modifiable command definition with the given unique id.

Protected version of at().

Parameters
uidCommand unique id.
Returns
Command definition reference.

Definition at line 1918 of file CommandLine.cxx.

References m_cmdDefs, and rnr::cmd::nocmddef.

Referenced by addCommand(), execute(), match(), and removeCommand().

1919 {
1920  CmdDefIter pos;
1921 
1922  if( (pos = m_cmdDefs.find(uid)) != m_cmdDefs.end() )
1923  {
1924  return pos->second;
1925  }
1926  else
1927  {
1928  return nocmddef;
1929  }
1930 }
static CmdDef nocmddef
"no cmd def" command definition
CmdDefMap::iterator CmdDefIter
cmd iterator type
Definition: CommandLine.h:417
CmdDefMap m_cmdDefs
map of added command definitions
Definition: CommandLine.h:1191
CmdDef& rnr::cmd::CommandLine::cmdAt ( const std::string &  strName)
protected

Get modifiable command definition with the given argv0 name.

Protected version of at().

Parameters
strNameCommand name.
Returns
Command definition reference.
int CommandLine::compile ( )
virtual

Compile all added commands.

Compiling essentially parses the command extended usage syntax and sets the internal data for:

  • readline tab completion
  • input to command pattern matching
  • first-level command validation
Returns
On success, AOk(0) is returned. On error, a CommandLine error code (< 0) is returned. See getErroStr() and backtrace() to retrieve or print error(s).

Definition at line 627 of file CommandLine.cxx.

References rnr::cmd::AOk, rnr::bookmark(), rnr::LogBook::clear(), rnr::cmd::EError, rnr::eoe(), finalize(), getErrorStr(), LOGERROR_STREAM, m_bIsCompiled, m_cmdDefs, m_log, m_nUidCnt, m_readline, numOfCmds(), rnr::cmd::ReadLine::registerAltGenerator(), rlBuildReadLineGenerator(), and rlGeneratorWrapper().

Referenced by execTAdd(), execTCompile(), and loadCommands().

628 {
629  CmdDefIter iter;
630  int rc = AOk;
631 
632  CL_DBG_CALL_IN("", endl);
633 
634  m_bIsCompiled = false;
635 
636  m_log.clear();
637  m_log << bookmark(markExec) << labelExec << __func__ << eoe;
638 
639  //
640  // No commands added.
641  //
642  if( m_nUidCnt == 0 )
643  {
644  m_log << labelFail << "No commands added." << eoe;
646  rc = EError;
647  }
648 
649  //
650  // Compile each command.
651  //
652  for(iter = m_cmdDefs.begin();
653  (rc == AOk) && (iter != m_cmdDefs.end());
654  ++iter)
655  {
656  CmdDef &cmddef = iter->second;
657 
658  if( !cmddef.isDefined() )
659  {
660  rc = compile(cmddef);
661  }
662  }
663 
664  //
665  // Finalize compilation.
666  //
667  if( rc == AOk )
668  {
669  rc = finalize();
670  }
671 
672  //
673  // Build readline generator.
674  //
675  if( rc == AOk )
676  {
678  }
679 
680  //
681  // All good.
682  //
683  if( rc == AOk )
684  {
685  // register readline generator callback
687 
688  m_bIsCompiled = true;
689 
690  m_log.clear();
691  m_log << bookmark(markExec) << labelExec << __func__ << eoe;
692  m_log << labelCompile << "Compiled " << numOfCmds() << " commands." << eoe;
693  m_log << labelExec << "Ok" << eoe;
694  }
695 
696  CL_DBG_CALL_OUT_NL("rc=" << rc);
697 
698  return rc;
699 }
virtual int rlBuildReadLineGenerator()
Perform any necessary pre-processing to prepare for command line TAB completion.
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
void registerAltGenerator(AltAppGenFunc fnAltAppGen, void *pAppArg)
Register alternate application-specific tab-completion generator.
Definition: ReadLine.cxx:155
ReadLine m_readline
readline interface
Definition: CommandLine.h:1194
bool m_bIsCompiled
has [not] been successfully compiled
Definition: CommandLine.h:1190
void clear()
Clear the log book and bookmarks, along with any pending entry.
Definition: LogBook.cxx:521
virtual int compile()
Compile all added commands.
int numOfCmds() const
Get the total number of added commands.
Definition: CommandLine.h:1108
const int EError
general, unspecified error
Definition: CmdCore.h:99
Compiled command definition class.
Definition: CmdDef.h:88
int finalize()
Finalize command compilation.
CmdDefMap::iterator CmdDefIter
cmd iterator type
Definition: CommandLine.h:417
LogBook & eoe(LogBook &log)
LogBook end-of-entry stream manipulator.
Definition: LogBook.cxx:926
const int AOk
(0) A-Ok, no error, success, good
Definition: CmdCore.h:93
#define LOGERROR_STREAM(args)
Error stream logging.
Definition: LogStream.h:167
LogBook & bookmark(LogBook &log)
LogBook bookmark stream manipulator.
Definition: LogBook.cxx:932
static const std::string rlGeneratorWrapper(void *pAppArg, const std::string &strText, int nIndex, const std::string &strContext, int nStart, int nEnd, unsigned &uFlags)
Static TAB completion generator wrapper.
int m_nUidCnt
unique id counter
Definition: CommandLine.h:1189
const std::string & getErrorStr() const
Get the most recent error.
CmdDefMap m_cmdDefs
map of added command definitions
Definition: CommandLine.h:1191
int CommandLine::compile ( CmdDef cmddef)
protectedvirtual

Compile a command.

See also
CommandLine::compile()
Parameters
cmddefCommand definition.
Returns
On success, AOk(0) is returned. On error, a CommandLine error code (< 0) is returned. See getErroStr() and backtrace() to retrieve or print error(s).

Definition at line 701 of file CommandLine.cxx.

References rnr::cmd::AOk, rnr::bookmark(), rnr::LogBook::clear(), rnr::cmd::EBadSyntax, rnr::eoe(), rnr::cmd::CmdDef::formAt(), getErrorStr(), rnr::cmd::CmdFormDef::getIndex(), rnr::cmd::CmdDef::getName(), rnr::cmd::CmdFormDef::getSyntax(), rnr::cmd::CmdDef::getUid(), LOGERROR_STREAM, m_log, rnr::cmd::CmdDef::m_nUid, rnr::cmd::CmdDef::numOfForms(), parseSyntax(), rnr::cmd::CmdDef::reset(), and tokenizeSyntax().

702 {
703  TokenVec tokens;
704  ssize_t tokcnt;
705  int i;
706  int rc;
707 
708  CL_DBG_CALL_IN("cmddef.uid=" << cmddef.getUid(), " ***" << endl);
709 
710  m_log.clear();
711  m_log << bookmark(markExec) << labelExec << __func__ << eoe;
712  m_log << labelCompile << "cmddef " << cmddef.getUid()
713  << ": " << cmddef.getName() << eoe;
714 
715  // reset command definition to pre-compiled state
716  cmddef.reset();
717 
718  for(i = 0, rc = AOk; (i < cmddef.numOfForms()) && (rc == AOk); ++i)
719  {
720  CmdFormDef &form = cmddef.formAt(i);
721 
722  if( (tokcnt = tokenizeSyntax(form.getSyntax(), tokens)) < 0 )
723  {
724  rc = tokcnt;
725  }
726 
727  else if( tokcnt == 0 )
728  {
729  m_log << labelFail
730  << "cmddef " << cmddef.m_nUid << ", "
731  << "form " << form.getIndex() << ": No syntax specified." << eoe;
733  rc = EBadSyntax;
734  }
735 
736  else
737  {
738  rc = parseSyntax(cmddef, form, tokens);
739  }
740  }
741 
742  if( rc == AOk )
743  {
744  m_log << labelExec << "Ok" << eoe;
745  }
746  else
747  {
748  m_log << labelFail << "Could not compile." << eoe;
749  }
750 
751  CL_DBG_CALL_OUT_NL("rc=" << rc);
752  CL_DBG(endl);
753 
754  return rc;
755 }
CmdFormDef & formAt(const int nIndex)
Get command modifiable form at index.
Definition: CmdDef.cxx:187
void reset()
Reset command definition to pre-compiled state.
Definition: CmdDef.cxx:134
int getUid() const
Get command&#39;s unique id.
Definition: CmdDef.h:134
int m_nUid
command unique id
Definition: CmdDef.h:228
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
virtual ssize_t tokenizeSyntax(const std::string &strSyntax, TokenVec &tokens)
Lexically analyze extened usage syntax string to generate a series of tokens.
void clear()
Clear the log book and bookmarks, along with any pending entry.
Definition: LogBook.cxx:521
std::vector< Token > TokenVec
vector of tokens type
Definition: Token.h:222
virtual int parseSyntax(CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens)
Parse command syntax.
int getIndex() const
Get forms&#39;s index.
Definition: CmdFormDef.h:152
LogBook & eoe(LogBook &log)
LogBook end-of-entry stream manipulator.
Definition: LogBook.cxx:926
const int EBadSyntax
bad syntax
Definition: CmdCore.h:104
const int AOk
(0) A-Ok, no error, success, good
Definition: CmdCore.h:93
#define LOGERROR_STREAM(args)
Error stream logging.
Definition: LogStream.h:167
LogBook & bookmark(LogBook &log)
LogBook bookmark stream manipulator.
Definition: LogBook.cxx:932
const std::string & getName() const
Return command&#39;s name.
Definition: CmdDef.h:144
int numOfForms() const
Get the total number command forms.
Definition: CmdDef.h:184
std::string getSyntax() const
Get form&#39;s extended usage syntax.
Definition: CmdFormDef.h:160
Compiled command form defintion class.
Definition: CmdFormDef.h:91
const std::string & getErrorStr() const
Get the most recent error.
CmdDefCIter rnr::cmd::CommandLine::end ( ) const
inline

Return a constant iterator referring to the past-the-end element of the list of command definitions.

Returns
Constant Iterator.

Definition at line 1130 of file CommandLine.h.

References rnr::str::c14n(), and rnr::cmd::CmdExec::operator<<.

Referenced by rnr::cmd::addons::execHelp().

1131  {
1132  return m_cmdDefs.end();
1133  }
CmdDefMap m_cmdDefs
map of added command definitions
Definition: CommandLine.h:1191
int CommandLine::execute ( const str::StringVec argv)
virtual

Execute a comamnd with the given arguments.

Parameters
argvThe list of string arguments.
Returns
Returns a Command Error Codes on failure to find the associated command or its execution function. Otherwise, returns the user-define execution function return value.

Definition at line 984 of file CommandLine.cxx.

References cmdAt(), rnr::cmd::EBadSyntax, rnr::cmd::EUnknownCmd, rnr::cmd::CmdDef::getUid(), m_cmdExecs, and rnr::cmd::NoUid.

Referenced by run().

985 {
986  int uid;
987  CmdExecIter pos;
988 
989  // no command nor arguments
990  if( argv.size() == 0 )
991  {
992  return EBadSyntax;
993  }
994 
995  // find the added command by name (the first argument)
996  CmdDef &cmd = cmdAt(argv[0]);
997 
998  // get the command's unique id
999  uid = cmd.getUid();
1000 
1001  // no command added with this uid
1002  if( uid == NoUid )
1003  {
1004  return EUnknownCmd;
1005  }
1006 
1007  // find the uid associated command execution function
1008  if( (pos = m_cmdExecs.find(uid)) == m_cmdExecs.end() )
1009  {
1010  // no execution function
1011  return EUnknownCmd;
1012  }
1013 
1014  // execute
1015  return pos->second.execute(argv);
1016 }
const int EUnknownCmd
unknown, unmatched command
Definition: CmdCore.h:103
CmdExecMap::iterator CmdExecIter
exec iterator type
Definition: CommandLine.h:424
int getUid() const
Get command&#39;s unique id.
Definition: CmdDef.h:134
const int NoUid
Special values.
Definition: CmdCore.h:116
Compiled command definition class.
Definition: CmdDef.h:88
CmdExecMap m_cmdExecs
map of added command executions
Definition: CommandLine.h:1192
const int EBadSyntax
bad syntax
Definition: CmdCore.h:104
CmdDef & cmdAt(const int uid)
Get modifiable command definition with the given unique id.
int CommandLine::execute ( const CmdExtArgVec argv)
virtual

Execute a comamnd with the given arguments.

Parameters
argvThe list of extended arguments.
Returns
Returns a Command Error Codes on failure to find the associated command or its execution function. Otherwise, returns the user-define execution function return value.

Definition at line 1018 of file CommandLine.cxx.

References rnr::cmd::EBadSyntax, rnr::cmd::EUnknownCmd, and m_cmdExecs.

1019 {
1020  CmdExecIter pos;
1021 
1022  // no command nor arguments
1023  if( argv.size() == 0 )
1024  {
1025  return EBadSyntax;
1026  }
1027 
1028  // find the uid associated command execution function
1029  if( (pos = m_cmdExecs.find(argv[0].uid())) == m_cmdExecs.end() )
1030  {
1031  // no execution function
1032  return EUnknownCmd;
1033  }
1034 
1035  // execute
1036  return pos->second.execute(*this, argv);
1037 }
const int EUnknownCmd
unknown, unmatched command
Definition: CmdCore.h:103
CmdExecMap::iterator CmdExecIter
exec iterator type
Definition: CommandLine.h:424
CmdExecMap m_cmdExecs
map of added command executions
Definition: CommandLine.h:1192
const int EBadSyntax
bad syntax
Definition: CmdCore.h:104
int CommandLine::finalize ( )
protected

Finalize command compilation.

Returns
On success, AOk(0) is returned. On error, a CommandLine error code (< 0) is returned. See getErroStr() and backtrace() to retrieve or print error(s).

Definition at line 757 of file CommandLine.cxx.

References rnr::cmd::AOk, rnr::cmd::EAmbigCmd, rnr::eoe(), getErrorStr(), rnr::cmd::CmdDef::getName(), rnr::cmd::CmdDef::getUid(), LOGERROR_STREAM, m_cmdDefs, and m_log.

Referenced by compile().

758 {
759  CmdDefIter iter, jter; // command definition iterators
760 
761  for(iter = m_cmdDefs.begin(); iter != m_cmdDefs.end(); ++iter)
762  {
763  CmdDef &cmddef_i = iter->second;
764 
765  jter = iter;
766 
767  for(++jter; jter != m_cmdDefs.end(); ++jter)
768  {
769  CmdDef &cmddef_j = jter->second;
770 
771  if( cmddef_i.getName() == cmddef_j.getName() )
772  {
773  m_log << labelSyntax << "Duplicate command names found at uid's "
774  << cmddef_i.getUid() << " and " << cmddef_j.getUid() << "."
775  << eoe;
777  return EAmbigCmd;
778  }
779  }
780  }
781 
782  return AOk;
783 }
int getUid() const
Get command&#39;s unique id.
Definition: CmdDef.h:134
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
const int EAmbigCmd
ambiguous command
Definition: CmdCore.h:102
Compiled command definition class.
Definition: CmdDef.h:88
CmdDefMap::iterator CmdDefIter
cmd iterator type
Definition: CommandLine.h:417
LogBook & eoe(LogBook &log)
LogBook end-of-entry stream manipulator.
Definition: LogBook.cxx:926
const int AOk
(0) A-Ok, no error, success, good
Definition: CmdCore.h:93
#define LOGERROR_STREAM(args)
Error stream logging.
Definition: LogStream.h:167
const std::string & getName() const
Return command&#39;s name.
Definition: CmdDef.h:144
const std::string & getErrorStr() const
Get the most recent error.
CmdDefMap m_cmdDefs
map of added command definitions
Definition: CommandLine.h:1191
CmdArgDef::ArgType CommandLine::getArgDefType ( const CmdExtArg arg) const

Get the argument type.

The extended argument contains matched command context.

Note
Argument type differs from argument converted type. The former specifies the argument syntax, while the later specifies converted basic type such as string, int, etc.
Parameters
argExtended argument.
Returns
Returns argument type.

Definition at line 1580 of file CommandLine.cxx.

References rnr::cmd::CmdExtArg::argIndex(), at(), rnr::cmd::CmdExtArg::formIndex(), rnr::cmd::CmdArgDef::getType(), and rnr::cmd::CmdExtArg::uid().

1581 {
1582  const CmdArgDef &argdef= at(arg.uid()).at(arg.formIndex()).at(arg.argIndex());
1583 
1584  return argdef.getType();
1585 }
int formIndex() const
Get the argument&#39;s associated parsed form definition index.
Definition: CmdExtArg.h:165
Command argument compiled definition class.
Definition: CmdArgDef.h:89
int uid() const
Get the argument&#39;s associated parsed command unique id.
Definition: CmdExtArg.h:158
const CmdDef & at(const int uid) const
Get the command definition with the unique id.
ArgType getType() const
Get argument&#39;s type.
Definition: CmdArgDef.h:214
int argIndex() const
Get the argument&#39;s associated parsed argument definition index.
Definition: CmdExtArg.h:172
const string & CommandLine::getArgName ( const CmdExtArg arg) const

Get the argument name.

The extended argument contains matched command context.

Parameters
argExtended argument.
Returns
Returns argument name on success, empty string on failure.

Definition at line 1572 of file CommandLine.cxx.

References rnr::cmd::CmdExtArg::argIndex(), at(), rnr::cmd::CmdExtArg::formIndex(), rnr::cmd::CmdArgDef::getName(), and rnr::cmd::CmdExtArg::uid().

1573 {
1574  // all terrain armored transport, of course
1575  const CmdArgDef &argdef= at(arg.uid()).at(arg.formIndex()).at(arg.argIndex());
1576 
1577  return argdef.getName();
1578 }
int formIndex() const
Get the argument&#39;s associated parsed form definition index.
Definition: CmdExtArg.h:165
Command argument compiled definition class.
Definition: CmdArgDef.h:89
int uid() const
Get the argument&#39;s associated parsed command unique id.
Definition: CmdExtArg.h:158
const CmdDef & at(const int uid) const
Get the command definition with the unique id.
const std::string & getName() const
Get argument&#39;s name.
Definition: CmdArgDef.h:204
int argIndex() const
Get the argument&#39;s associated parsed argument definition index.
Definition: CmdExtArg.h:172
bool rnr::cmd::CommandLine::getBtEnable ( ) const
inline

Test if backtracing is enabled.

Returns
Returns true or false.

Definition at line 499 of file CommandLine.h.

References rnr::cmd::DataSectNsCore.

Referenced by readCommand().

500  {
501  return
502  ((DataSectCore*)m_dataSects.at(DataSectNsCore).data())->m_bBacktrace;
503  }
const char *const DataSectNsCore
Reserved command line data section namespaces.
Definition: CmdCore.h:141
DataSectMap m_dataSects
data sections
Definition: CommandLine.h:1196
void * CommandLine::getDataSection ( const std::string &  ns)

Get the section data under the specified namespace.

Parameters
nsNamespace of data section to retrieve.
Returns
Returns pointer to the data if it exist. NULL is returned if no namespace is found, or no data has been specified.

Definition at line 830 of file CommandLine.cxx.

References m_dataSects.

831 {
832  DataSectIter pos = m_dataSects.find(ns);
833 
834  return pos != m_dataSects.end()? pos->second.data(): NULL;
835 }
DataSectMap::iterator DataSectIter
iterator type
Definition: CommandLine.h:431
DataSectMap m_dataSects
data sections
Definition: CommandLine.h:1196
const string & CommandLine::getErrorStr ( ) const

Get the most recent error.

Returns
Error string.

Definition at line 1947 of file CommandLine.cxx.

References rnr::LogBook::lastText(), and m_log.

Referenced by addCommand(), compile(), execTAdd(), execTCompile(), execTPrint(), execTRemove(), finalize(), lexSyntaxParenExpr(), lexSyntaxWord(), parseArg(), parseArgv0(), parseIdentifier(), parseLiteralValue(), parseSyntax(), parseVarMod(), parseVarRangeExpr(), parseVarRegExpr(), parseVarType(), parseXorList(), readCommand(), removeCommand(), tokEq(), and tokIdentifier().

1948 {
1949  return m_log.lastText();
1950 }
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
const std::string & lastText() const
Get the last (latest) log entry text.
Definition: LogBook.h:523
size_t rnr::cmd::CommandLine::getLineNum ( ) const
inline

Get the line number of the last read line.

Returns
Line number.

Definition at line 853 of file CommandLine.h.

Referenced by pushToken(), and readCommand().

854  {
855  return m_readline.getLineNum();
856  }
size_t getLineNum() const
Get the line number of the last read line.
Definition: ReadLine.h:443
ReadLine m_readline
readline interface
Definition: CommandLine.h:1194
const std::string& rnr::cmd::CommandLine::getName ( ) const
inline

Get command line interface's name.

Returns
Name string.

Definition at line 1040 of file CommandLine.h.

Referenced by execTPrint(), and readCommand().

1041  {
1042  return m_strName;
1043  }
std::string m_strName
name of this command line
Definition: CommandLine.h:1187
const string & CommandLine::getPrompt ( ) const

Get the current prompt string.

Returns
String.

Definition at line 1071 of file CommandLine.cxx.

References m_prompts, and rnr::cmd::noprompt.

Referenced by c14n(), execTPrint(), and popPrompt().

1072 {
1073  if( !m_prompts.empty() )
1074  {
1075  return m_prompts.back();
1076  }
1077  else
1078  {
1079  return noprompt;
1080  }
1081 }
static const string noprompt
"no prompt" prompt value
PromptStack m_prompts
stack of prompt strings
Definition: CommandLine.h:1193
bool CommandLine::hasCmd ( const int  uid) const

Test if command exists.

Parameters
uidCommand unique id.
Returns
Returns true or false.

Definition at line 1879 of file CommandLine.cxx.

References at(), and m_cmdDefs.

Referenced by execTAdd().

1880 {
1881  return m_cmdDefs.find(uid) != m_cmdDefs.end();
1882 }
CmdDefMap m_cmdDefs
map of added command definitions
Definition: CommandLine.h:1191
bool rnr::cmd::CommandLine::hasCmd ( const std::string &  strName) const

Test if command exists.

Parameters
strNameCommand name.
Returns
Returns true or false.
bool CommandLine::isReservedDataSection ( const std::string &  ns) const

Test if the namespace is a command-line interface reserved name.

Parameters
nsNamespace.
Returns
Returns true or false.

Definition at line 837 of file CommandLine.cxx.

References rnr::cmd::DataSectNsCore, rnr::cmd::DataSectNsNet, and rnr::cmd::DataSectNsOS.

Referenced by removeDataSection().

838 {
839  return (ns == DataSectNsCore) || (ns == DataSectNsOS) ||
840  (ns == DataSectNsNet);
841 }
const char *const DataSectNsNet
network data section ns
Definition: CmdCore.h:143
const char *const DataSectNsCore
Reserved command line data section namespaces.
Definition: CmdCore.h:141
const char *const DataSectNsOS
OS data section ns.
Definition: CmdCore.h:142
ssize_t CommandLine::lexQuotedString ( const std::string &  strInput,
ssize_t  cursor,
TokenVec tokens 
)
protectedvirtual

Quoted string lexical analyzer.

The unescaped double quotes are not included in the token. Escape sequences interpreted.

On success, the generated <interp-char-seq> token is placed at the end of the vector.

Syntax:
<quoted-string> ::= '"' <interp-char-seq> '"'
<interp-char-seq> ::= <interp-char>
| <interp-char-seq> <interp-char>
<interp-char> ::= NON_BACKSLASH_CHAR
| <interp-esc-char>
<interp-esc-char> ::= '\' CHAR
| '\' 'x' HEXDIGIT
| '\' 'x' HEXDIGIT HEXDIGIT
Parameters
[in]strInputInput string to analyze.
[in]cursorCharacter position along input string.
[in,out]tokensVector of generated tokens.
Returns
On success, returns new cursor position. Otherwise a negative error code is returned.

Definition at line 2256 of file CommandLine.cxx.

References rnr::cmd::EBadSyntax, rnr::eoe(), rnr::cmd::isdquote(), logLexToken(), m_log, pushToken(), and rnr::cmd::tohex().

Referenced by backtrace().

2259 {
2260  size_t len; // length of input string;
2261  size_t start; // start character position of token in input string
2262  bool escseq; // is [not] in an escape sequence
2263  bool eos; // is [not] at end of string
2264  char c; // working converted character
2265  string value; // working token value
2266 
2267  len = strInput.length();
2268 
2269  if( isdquote(strInput[cursor]) )
2270  {
2271  ++cursor;
2272  start = cursor;
2273  }
2274  else
2275  {
2276  logLexToken(strInput, cursor, cursor, tokens);
2277  m_log << labelSyntax << "No starting double qoute '\"' found." << eoe;
2278  return EBadSyntax;
2279  }
2280 
2281  escseq = false;
2282  eos = false;
2283 
2284  while( (cursor >= 0) && (cursor < len) && !eos )
2285  {
2286  // escape sequence
2287  if( escseq )
2288  {
2289  switch( strInput[cursor] )
2290  {
2291  case 't': // tab
2292  c = '\t';
2293  break;
2294  case 'n': // newline
2295  c = '\n';
2296  break;
2297  case 'r': // carriage return
2298  c = '\r';
2299  break;
2300  case 'v': // vertical tab
2301  c = '\v';
2302  break;
2303  case 'f': // formfeed
2304  c = '\f';
2305  break;
2306  case 'x': // h[h]
2307  {
2308  int i = cursor + 1;
2309  if( (i < len) && isxdigit(strInput[i]) )
2310  {
2311  c = tohex(strInput[i]);
2312  ++cursor;
2313  ++i;
2314  if( (i < len) && isxdigit(strInput[i]) )
2315  {
2316  c <<= 4;
2317  c |= tohex(strInput[i]);
2318  ++cursor;
2319  }
2320  }
2321  else
2322  {
2323  c = 'x';
2324  }
2325  }
2326  break;
2327  default:
2328  c = strInput[cursor];
2329  break;
2330  }
2331 
2332  value.push_back(c);
2333  escseq = false;
2334  ++cursor;
2335  }
2336 
2337  else
2338  {
2339  switch( strInput[cursor] )
2340  {
2341  case '\\':
2342  escseq = true;
2343  break;
2344  case '"':
2345  eos = true;
2346  break;
2347  default:
2348  value.push_back(strInput[cursor++]);
2349  break;
2350  }
2351  }
2352  }
2353 
2354  if( isdquote(strInput[cursor]) )
2355  {
2356  pushToken(strInput, start, cursor, tokens);
2357 
2358  ++cursor; // get past quote
2359 
2360  return cursor;
2361  }
2362  else
2363  {
2364  logLexToken(strInput, start, cursor, tokens);
2365  m_log << labelSyntax << "No ending double qoute '\"' found." << eoe;
2366  return EBadSyntax;
2367  }
2368 }
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
static char tohex(int c)
Convert ascii character to binary character value.
static bool isdquote(int c)
Test if c is a double quote character.
virtual void logLexToken(const std::string &strSource, const size_t start, const ssize_t cursor, TokenVec &tokens, const bool bLoc=false)
Log lexigraphical token.
LogBook & eoe(LogBook &log)
LogBook end-of-entry stream manipulator.
Definition: LogBook.cxx:926
const int EBadSyntax
bad syntax
Definition: CmdCore.h:104
void pushToken(const std::string &strSource, const size_t start, const ssize_t cursor, TokenVec &tokens)
Push token to the end of the generated tokens.
ssize_t CommandLine::lexSyntaxParenExpr ( const std::string &  strSyntax,
ssize_t  cursor,
TokenVec tokens 
)
protectedvirtual

Syntax parenthetical expression lexical analyzer.

A syntax parenthetical expression isdefined as any contiguous sequence block of character delineated by a balanced pair of parentheses. A backslash escaped parenthesis does to factor into the paentheses countiog.

On success,the generated tokens '(', <paren-tok>, and ')' are placed at the end of the vector.

Syntax:
<paren-expr-def> ::= '(' <paren-tok> ')'
Parameters
[in]strSyntaxSyntax string to analyze.
[in]cursorCharacter position along syntax string.
[in,out]tokensVector of generated tokens.
Returns
On success, returns new cursor position. Otherwise a negative error code is returned.

Definition at line 2137 of file CommandLine.cxx.

References rnr::cmd::EBadSyntax, rnr::eoe(), getErrorStr(), rnr::cmd::iscparen(), rnr::cmd::isoparen(), LOGERROR_STREAM, logLexToken(), m_log, and pushToken().

Referenced by tokenizeSyntax().

2140 {
2141  size_t len; // length of input string;
2142  size_t start; // start character position of token in input string
2143  int pdepth; // parenthesis depth
2144  bool escseq; // is [not] in an escape sequence
2145  bool eop; // is [not] at end of parenthetical
2146  char c; // working character
2147  string value; // working token value
2148 
2149  len = strSyntax.length();
2150  start = cursor;
2151  pdepth = 0;
2152  escseq = false;
2153  eop = false;
2154 
2155  if( isoparen(strSyntax[cursor]) )
2156  {
2157  // '(' token
2158  start = cursor++;
2159  pushToken(strSyntax, start, cursor, tokens);
2160 
2161  start = cursor;
2162  ++pdepth;
2163  }
2164  else
2165  {
2166  logLexToken(strSyntax, start, cursor, tokens);
2167  m_log << labelSyntax << "No starting '(' found." << eoe;
2169  return EBadSyntax;
2170  }
2171 
2172  while( (cursor >= 0) && (cursor < len) && !eop )
2173  {
2174  switch( strSyntax[cursor] )
2175  {
2176  case '\\':
2177  escseq = true;
2178  break;
2179  case '(':
2180  if( !escseq )
2181  {
2182  ++pdepth;
2183  }
2184  escseq = false;
2185  break;
2186  case ')':
2187  if( !escseq )
2188  {
2189  if( --pdepth == 0 )
2190  {
2191  eop = true;
2192  }
2193  }
2194  escseq = false;
2195  break;
2196  default:
2197  escseq = false;
2198  break;
2199  }
2200 
2201  if( !eop )
2202  {
2203  value.push_back(strSyntax[cursor++]);
2204  }
2205  }
2206 
2207  if( iscparen(strSyntax[cursor]) )
2208  {
2209  // expression token
2210  pushToken(strSyntax, start, cursor, tokens);
2211 
2212  // ')' token
2213  start = cursor++;
2214  pushToken(strSyntax, start, cursor, tokens);
2215 
2216  return cursor;
2217  }
2218  else
2219  {
2220  logLexToken(strSyntax, start, cursor, tokens);
2221  m_log << labelSyntax << "No ending ')' found." << eoe;
2223  return EBadSyntax;
2224  }
2225 }
static bool isoparen(int c)
Test if c is a open parenthesis character.
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
static bool iscparen(int c)
Test if c is a close parenthesis character.
virtual void logLexToken(const std::string &strSource, const size_t start, const ssize_t cursor, TokenVec &tokens, const bool bLoc=false)
Log lexigraphical token.
LogBook & eoe(LogBook &log)
LogBook end-of-entry stream manipulator.
Definition: LogBook.cxx:926
const int EBadSyntax
bad syntax
Definition: CmdCore.h:104
#define LOGERROR_STREAM(args)
Error stream logging.
Definition: LogStream.h:167
const std::string & getErrorStr() const
Get the most recent error.
void pushToken(const std::string &strSource, const size_t start, const ssize_t cursor, TokenVec &tokens)
Push token to the end of the generated tokens.
ssize_t CommandLine::lexSyntaxWord ( const std::string &  strSyntax,
ssize_t  cursor,
TokenVec tokens 
)
protectedvirtual

Syntax word lexical analyzer.

A syntax word is defined as any contiguous sequence of non-whitespace, non-syntax-special symbol characters.

On success, the generated <word> token is placed at the end of the vector.

Parameters
[in]strSyntaxSyntax string to analyze.
[in]cursorCharacter position along syntax string.
[in,out]tokensVector of generated tokens.
Returns
On success, returns new cursor position. Otherwise a negative error code is returned.

Definition at line 2104 of file CommandLine.cxx.

References rnr::cmd::EBadSyntax, rnr::eoe(), getErrorStr(), rnr::cmd::isspecial(), LOGERROR_STREAM, logLexToken(), m_log, and pushToken().

Referenced by tokenizeSyntax().

2107 {
2108  size_t len;
2109  size_t start;
2110 
2111  len = strSyntax.length();
2112  start = cursor;
2113 
2114  // find end of word
2115  while( (cursor < len) &&
2116  !isspace((int)strSyntax[cursor]) &&
2117  !isspecial(strSyntax[cursor]) )
2118  {
2119  ++cursor;
2120  }
2121 
2122  if( cursor > start )
2123  {
2124  pushToken(strSyntax, start, cursor, tokens);
2125  }
2126  else
2127  {
2128  logLexToken(strSyntax, start, cursor, tokens);
2129  m_log << labelSyntax << "No <word> found." << eoe;
2131  cursor = EBadSyntax;
2132  }
2133 
2134  return cursor;
2135 }
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
virtual void logLexToken(const std::string &strSource, const size_t start, const ssize_t cursor, TokenVec &tokens, const bool bLoc=false)
Log lexigraphical token.
LogBook & eoe(LogBook &log)
LogBook end-of-entry stream manipulator.
Definition: LogBook.cxx:926
const int EBadSyntax
bad syntax
Definition: CmdCore.h:104
#define LOGERROR_STREAM(args)
Error stream logging.
Definition: LogStream.h:167
static bool isspecial(int c)
Command usage syntax special characters.
const std::string & getErrorStr() const
Get the most recent error.
void pushToken(const std::string &strSource, const size_t start, const ssize_t cursor, TokenVec &tokens)
Push token to the end of the generated tokens.
ssize_t CommandLine::lexWord ( const std::string &  strInput,
ssize_t  cursor,
TokenVec tokens 
)
protectedvirtual

Word lexical analyzer.

A word is defined as any contiguous sequence of non-whitespace characters.

On success, the generated <word> token is placed at the end of the vector.

Parameters
[in]strInputInput string to analyze.
[in]cursorCharacter position along input string.
[in,out]tokensVector of generated tokens.
Returns
On success, returns new cursor position. Otherwise a negative error code is returned.

Definition at line 2227 of file CommandLine.cxx.

References rnr::cmd::EBadSyntax, rnr::eoe(), logLexToken(), m_log, and pushToken().

Referenced by backtrace().

2230 {
2231  size_t len;
2232  size_t start;
2233 
2234  len = strInput.length();
2235  start = cursor;
2236 
2237  while( (cursor < len) && !isspace((int)strInput[cursor]) )
2238  {
2239  ++cursor;
2240  }
2241 
2242  if( cursor > start )
2243  {
2244  pushToken(strInput, start, cursor, tokens);
2245  }
2246  else
2247  {
2248  logLexToken(strInput, start, cursor, tokens);
2249  m_log << labelSyntax << "No <word> found." << eoe;
2250  cursor = EBadSyntax;
2251  }
2252 
2253  return cursor;
2254 }
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
virtual void logLexToken(const std::string &strSource, const size_t start, const ssize_t cursor, TokenVec &tokens, const bool bLoc=false)
Log lexigraphical token.
LogBook & eoe(LogBook &log)
LogBook end-of-entry stream manipulator.
Definition: LogBook.cxx:926
const int EBadSyntax
bad syntax
Definition: CmdCore.h:104
void pushToken(const std::string &strSource, const size_t start, const ssize_t cursor, TokenVec &tokens)
Push token to the end of the generated tokens.
void CommandLine::logLexToken ( const std::string &  strSource,
const size_t  start,
const ssize_t  cursor,
TokenVec tokens,
const bool  bLoc = false 
)
protectedvirtual

Log lexigraphical token.

Parameters
strSourceSource string of tokens.
startStart token character position in source.
cursorCursor position in source.
[in,out]tokensVector of lexical tokens.
bLocIf true, then include line number and token characater positions.

Definition at line 2370 of file CommandLine.cxx.

References rnr::eoe(), m_log, and pushToken().

Referenced by lexQuotedString(), lexSyntaxParenExpr(), lexSyntaxWord(), and lexWord().

2375 {
2376  stringstream ss;
2377 
2378  pushToken(strSource, start, cursor, tokens);
2379  tokens.back().printAnnotated(ss, strSource);
2380  m_log << labelAt << ss.str() << eoe;
2381 }
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
LogBook & eoe(LogBook &log)
LogBook end-of-entry stream manipulator.
Definition: LogBook.cxx:926
void pushToken(const std::string &strSource, const size_t start, const ssize_t cursor, TokenVec &tokens)
Push token to the end of the generated tokens.
int CommandLine::match ( const TokenVec tokens,
CmdExtArgVec argv 
)
protected

Match the input tokens to the compiled commands to find the best fit.

Parameters
[in]tokensVector of input tokens.
[out]argvVector of extended arguments, with argv[0] being the command name argument.
Returns
On success, AOk(0) is returned. On error, a CommandLine error code (< 0) is returned. See getErroStr() and backtrace() to retrieve or print error(s).

Definition at line 1128 of file CommandLine.cxx.

References rnr::cmd::AOk, c14n(), cmdAt(), rnr::cmd::EAmbigCmd, rnr::cmd::EArgv0, rnr::cmd::EError, rnr::eoe(), rnr::cmd::EUnknownCmd, rnr::cmd::CmdDef::formAt(), rnr::cmd::CmdFormDef::getSyntax(), m_cmdDefs, m_log, matchCommand(), rnr::cmd::NoIndex, and rnr::cmd::NoUid.

Referenced by processInput().

1129 {
1130  CmdDefIter iter; // command definition iterator
1131 
1132  double fUltFitness; // best fitness value
1133  int uidUlt; // best command unique id
1134  int iformUlt; // best form index
1135 
1136  double fPenultFitness; // second best fitness value
1137  int uid2nd; // seconds best command unique id
1138  int iform2nd; // second best form index
1139 
1140  CmdExtArgVec argvCmd; // working command extended arguments
1141  double fFitness; // working fitness
1142  int cnt; // count of commands matching argv0
1143  int rc; // return code
1144 
1145  // This is considered a bug.
1146  if( tokens.size() == 0 )
1147  {
1148  LOGERROR("Bug: No tokens.");
1149  return EError;
1150  }
1151 
1152  argvCmd.clear();
1153 
1154  fPenultFitness = fUltFitness = 0.0;
1155  uid2nd = uidUlt = NoUid;
1156  iform2nd = iformUlt = NoIndex;
1157 
1158  cnt = 0;
1159 
1160  //
1161  // Find the best and second best command fits.
1162  //
1163  for(iter = m_cmdDefs.begin(); iter != m_cmdDefs.end(); ++iter)
1164  {
1165  rc = matchCommand(iter->second, tokens, argvCmd, fFitness);
1166 
1167  switch( rc )
1168  {
1169  case AOk: // complete match
1170  ++cnt;
1171  break;
1172  case EArgv0: // argv0 not matched
1173  break;
1174  default: // argv0 matched, but args failed to match
1175  ++cnt;
1176  continue;
1177  }
1178 
1179  // Found a new best.
1180  if( fFitness > fUltFitness )
1181  {
1182  fPenultFitness = fUltFitness;
1183  uid2nd = uidUlt;
1184  iform2nd = iformUlt;
1185 
1186  argv = argvCmd;
1187  fUltFitness = fFitness;
1188  uidUlt = iter->second.getUid();
1189  iformUlt = argv[0].formIndex();
1190  }
1191 
1192  // Found a new second best, but not a new best.
1193  else if( fFitness > fPenultFitness )
1194  {
1195  fPenultFitness = fFitness;
1196  uid2nd = iter->second.getUid();
1197  iform2nd = argvCmd[0].formIndex();
1198  }
1199  }
1200 
1201  //
1202  // No interface match.
1203  //
1204  if( uidUlt == NoUid )
1205  {
1206  if( cnt > 0 )
1207  {
1208  m_log << labelNoMatch << c14n(tokens) << eoe;
1209  }
1210  else
1211  {
1212  m_log << labelSyntax << "Command " << tokens[0] << " not found." << eoe;
1213  }
1214  rc = EUnknownCmd;
1215  }
1216 
1217  //
1218  // Duplicate fitness.
1219  //
1220  else if( fUltFitness == fPenultFitness )
1221  {
1222  m_log << labelNoMatch
1223  << "Command '" << tokens[0] << "' ambiguous. Matches:"
1224  << eoe;
1225  m_log << labelBlank << cmdAt(uidUlt).formAt(iformUlt).getSyntax() << eoe;
1226  m_log << labelBlank << cmdAt(uid2nd).formAt(iform2nd).getSyntax() << eoe;
1227  rc = EAmbigCmd;
1228  }
1229 
1230  //
1231  // Got a unambiguous, matched command.
1232  //
1233  else
1234  {
1235  m_log << labelSelect << cmdAt(uidUlt).formAt(iformUlt).getSyntax() << eoe;
1236  rc = AOk;
1237  }
1238 
1239  return rc;
1240 }
CmdFormDef & formAt(const int nIndex)
Get command modifiable form at index.
Definition: CmdDef.cxx:187
const int EUnknownCmd
unknown, unmatched command
Definition: CmdCore.h:103
int matchCommand(const CmdDef &cmddef, const TokenVec &tokens, CmdExtArgVec &argv, double &fFitness)
Match best command form against input line argument list.
static std::string c14n(const TokenVec &tokens)
Canonicalization of a string.
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
const int EAmbigCmd
ambiguous command
Definition: CmdCore.h:102
const int NoUid
Special values.
Definition: CmdCore.h:116
const int EError
general, unspecified error
Definition: CmdCore.h:99
std::vector< CmdExtArg > CmdExtArgVec
vector of ext args type
Definition: CmdExtArg.h:397
CmdDefMap::iterator CmdDefIter
cmd iterator type
Definition: CommandLine.h:417
LogBook & eoe(LogBook &log)
LogBook end-of-entry stream manipulator.
Definition: LogBook.cxx:926
CmdDef & cmdAt(const int uid)
Get modifiable command definition with the given unique id.
const int NoIndex
no index
Definition: CmdCore.h:117
const int AOk
(0) A-Ok, no error, success, good
Definition: CmdCore.h:93
const int EArgv0
not this command argv0
Definition: CmdCore.h:106
std::string getSyntax() const
Get form&#39;s extended usage syntax.
Definition: CmdFormDef.h:160
CmdDefMap m_cmdDefs
map of added command definitions
Definition: CommandLine.h:1191
int CommandLine::matchCommand ( const CmdDef cmddef,
const TokenVec tokens,
CmdExtArgVec argv,
double &  fFitness 
)
protected

Match best command form against input line argument list.

Parameters
[in]cmddefCompiled command definition.
[in]tokensVector of arguments.
[out]argvVector of extended arguments, with argv[0] being the command name argument.
[out]fFitnessFitness of match [0.0 - 1.0].
Returns
On success, AOk(0) is returned. On error, a CommandLine error code (< 0) is returned. See getErroStr() and backtrace() to retrieve or print error(s).

Definition at line 1242 of file CommandLine.cxx.

References rnr::cmd::AOk, rnr::cmd::CmdFormDef::at(), rnr::cmd::CmdDef::at(), rnr::cmd::EArgv0, rnr::cmd::EBadSyntax, rnr::cmd::EError, rnr::eoe(), rnr::cmd::CmdDef::getName(), rnr::cmd::CmdFormDef::getSyntax(), m_log, rnr::cmd::CmdArgDef::match(), matchCommandForm(), rnr::cmd::NoIndex, and rnr::cmd::CmdDef::numOfForms().

Referenced by match().

1246 {
1247  CmdExtArgVec argvForm; // working form extended arguments
1248  double fMaxFitness; // working and best form fitness
1249  int iBest; // best form index
1250  int i; // working index
1251  int rc; // return code
1252 
1253  // This is considered a bug.
1254  if( tokens.size() == 0 )
1255  {
1256  LOGERROR("Bug: No tokens.");
1257  return EError;
1258  }
1259 
1260  argv.clear();
1261 
1262  fFitness = 0.0;
1263  fMaxFitness = 0.0;
1264  iBest = NoIndex;
1265 
1266  //
1267  // If argv0 doesn't match, don't try to apply matching algorithm to this
1268  // command.
1269  //
1270  // Note: All command forms must have the same argv0 argument type and value.
1271  //
1272  if( cmddef.at(0).at(0).match(tokens[0].value()) == 0.0 )
1273  {
1274  return EArgv0;
1275  }
1276 
1277  for(i = 0; i < cmddef.numOfForms(); ++i)
1278  {
1279  const CmdFormDef &form = cmddef.at(i);
1280 
1281  m_log << labelTry << form.getSyntax() << eoe;
1282 
1283  if( (rc = matchCommandForm(form, tokens, argvForm, fFitness)) == AOk )
1284  {
1285  if( fFitness > fMaxFitness )
1286  {
1287  argv = argvForm;
1288  fMaxFitness = fFitness;
1289  iBest = i;
1290  }
1291  }
1292 
1293  m_log << labelFit << fFitness << eoe;
1294 
1295  if( fMaxFitness >= 1.0 )
1296  {
1297  break;
1298  }
1299  }
1300 
1301  //
1302  // Found the best command form that matches the input.
1303  //
1304  if( iBest >= 0 )
1305  {
1306  m_log << labelMatch
1307  << "Command '" << cmddef.getName()
1308  << "', form " << iBest << ": Fitness " << fMaxFitness
1309  << eoe;
1310  fFitness = fMaxFitness;
1311  rc = AOk;
1312  }
1313 
1314  //
1315  // No fit.
1316  //
1317  else
1318  {
1319  m_log << labelNoMatch
1320  << "Command '" << cmddef.getName()
1321  << "', all forms."
1322  << eoe;
1323  rc = EBadSyntax;
1324  }
1325 
1326  return rc;
1327 }
int matchCommandForm(const CmdFormDef &form, const TokenVec &tokens, CmdExtArgVec &argv, double &fFitness)
Match command form against input line argument list.
double match(const std::string &strArg, const bool bIgnoreCase=false) const
Match argument string against argument definition pattern.
Definition: CmdArgDef.cxx:326
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
const CmdFormDef & at(const int nIndex) const
Get command form at index.
Definition: CmdDef.cxx:175
const int EError
general, unspecified error
Definition: CmdCore.h:99
std::vector< CmdExtArg > CmdExtArgVec
vector of ext args type
Definition: CmdExtArg.h:397
LogBook & eoe(LogBook &log)
LogBook end-of-entry stream manipulator.
Definition: LogBook.cxx:926
const int EBadSyntax
bad syntax
Definition: CmdCore.h:104
const int NoIndex
no index
Definition: CmdCore.h:117
const int AOk
(0) A-Ok, no error, success, good
Definition: CmdCore.h:93
const std::string & getName() const
Return command&#39;s name.
Definition: CmdDef.h:144
const int EArgv0
not this command argv0
Definition: CmdCore.h:106
int numOfForms() const
Get the total number command forms.
Definition: CmdDef.h:184
std::string getSyntax() const
Get form&#39;s extended usage syntax.
Definition: CmdFormDef.h:160
Compiled command form defintion class.
Definition: CmdFormDef.h:91
const CmdArgDef & at(const int nIndex) const
Get form&#39;s argument at index.
Definition: CmdFormDef.cxx:176
int CommandLine::matchCommandForm ( const CmdFormDef form,
const TokenVec tokens,
CmdExtArgVec argv,
double &  fFitness 
)
protected

Match command form against input line argument list.

Parameters
[in]formCompiled command form definition.
[in]tokensVector of arguments.
[out]argvVector of extended arguments, with argv[0] being the command name argument.
[out]fFitnessFitness of match [0.0 - 1.0].
Returns
On success, AOk(0) is returned. On error, a CommandLine error code (< 0) is returned. See getErroStr() and backtrace() to retrieve or print error(s).

Definition at line 1329 of file CommandLine.cxx.

References rnr::cmd::AOk, rnr::cmd::CmdArgDef::ArgTypeBoolean, rnr::cmd::CmdArgDef::ArgTypeFile, rnr::cmd::CmdArgDef::ArgTypeFpn, rnr::cmd::CmdArgDef::ArgTypeIdentifier, rnr::cmd::CmdArgDef::ArgTypeInteger, rnr::cmd::CmdArgDef::ArgTypeLiteral, rnr::cmd::CmdArgDef::ArgTypeMultiWord, rnr::cmd::CmdArgDef::ArgTypeRegEx, rnr::cmd::CmdArgDef::ArgTypeUndef, rnr::cmd::CmdArgDef::ArgTypeWord, rnr::cmd::CmdFormDef::at(), rnr::cmd::CmdArgDef::constructLiteralList(), rnr::cmd::CmdArgDef::constructRangeList(), rnr::cmd::CmdArgDef::convert(), rnr::cmd::EBadSyntax, rnr::cmd::EError, rnr::eoe(), rnr::cmd::CmdFormDef::getIndex(), rnr::cmd::CmdArgDef::getIndex(), rnr::cmd::CmdFormDef::getParentCmdUid(), rnr::cmd::CmdArgDef::getRanges(), rnr::cmd::CmdArgDef::getRegEx(), rnr::cmd::CmdArgDef::getType(), rnr::cmd::CmdArgDef::isOptional(), rnr::cmd::CmdArgDef::lookupArgSymbol(), m_bIgnoreCase, m_cmdDefs, m_log, rnr::cmd::CmdArgDef::match(), rnr::cmd::CmdFormDef::numOfArgs(), and rnr::cmd::CmdFormDef::numOfRequiredArgs().

Referenced by matchCommand().

1333 {
1334  int argcToks = (int)tokens.size(); // number of input tokens
1335  int argcForm = form.numOfArgs(); // form total number of arguments
1336  double fWeight, fDecay; // match weight and decay multiplier
1337  int iArg; // working form argument index
1338  int iTok; // working input tokens index
1339  int rc; // return code
1340 
1341  argv.clear();
1342 
1343  fFitness = 0.0;
1344  fDecay = 1.0;
1345 
1346  // command name (for logging)
1347  const string &strCmdName = m_cmdDefs[form.getParentCmdUid()].getName();
1348 
1349  //
1350  // Too many input arguments.
1351  //
1352  if( argcToks > argcForm )
1353  {
1354  m_log << labelNoMatch
1355  << "Command '" << strCmdName << "', "
1356  << "form " << form.getIndex() << ": "
1357  << "Too many arguments: "
1358  << argcToks << " specified, "
1359  << argcForm << " maximum."
1360  << eoe;
1361  return EBadSyntax;
1362  }
1363 
1364  //
1365  // Missing required input arguments.
1366  //
1367  else if( argcToks < form.numOfRequiredArgs() )
1368  {
1369  m_log << labelNoMatch
1370  << "Command '" << strCmdName << "', "
1371  << "form " << form.getIndex() << ": "
1372  << "Missing required arguments: "
1373  << argcToks << " specified, "
1374  << form.numOfRequiredArgs() << " required."
1375  << eoe;
1376  return EBadSyntax;
1377  }
1378 
1379  //
1380  // Match input arguments to form syntax.
1381  //
1382  for(iArg = 0, iTok = 0, rc = AOk;
1383  (iArg < argcForm) && (iTok < argcToks) && (rc == AOk);
1384  ++iArg)
1385  {
1386  const CmdArgDef &argdef = form.at(iArg);
1387 
1388  // try to match input token to argument sytax
1389  fWeight = argdef.match(tokens[iTok].value(), m_bIgnoreCase);
1390 
1391  // no match
1392  if( fWeight == 0.0 )
1393  {
1394  rc = EBadSyntax;
1395 
1396  // start log entry
1397  m_log << labelNoMatch
1398  << "Input argument " << tokens[iTok] << " doesn't match "
1399  << "command '" << strCmdName << "', "
1400  << "form " << form.getIndex() << ", "
1401  << (argdef.isOptional()? "(opt)": "")
1402  << "arg " << argdef.getIndex()
1403  << " definition."
1404  << eoe;
1405 
1406  //
1407  // Log reason of match failure.
1408  //
1409  switch( argdef.getType() )
1410  {
1412  m_log << labelBlank << " Not one of: "
1413  << argdef.constructLiteralList() << "."
1414  << eoe;
1415  break;
1416 
1422  m_log << labelBlank << " Not a "
1423  << "'" << CmdArgDef::lookupArgSymbol(argdef.getType())
1424  << "' type." << eoe;
1425  break;
1426 
1428  case CmdArgDef::ArgTypeFpn:
1429  m_log << labelBlank << " Not a "
1430  << "'" << CmdArgDef::lookupArgSymbol(argdef.getType())
1431  << "' type";
1432  if( argdef.getRanges().size() > 0 )
1433  {
1434  m_log << " or out of range " << argdef.constructRangeList();
1435  }
1436  m_log << "." << eoe;
1437  break;
1438 
1440  m_log << labelBlank << " Failed to match re: "
1441  << "'" << argdef.getRegEx() << "'."
1442  << eoe;
1443  break;
1444 
1446  default:
1447  LOGERROR("Bug: Unknown type %d.", argdef.getType());
1448  rc = EError;
1449  break;
1450  }
1451  }
1452 
1453  //
1454  // Good argument match.
1455  //
1456  if( rc == AOk )
1457  {
1458  m_log << labelMatch
1459  << "Input argument " << tokens[iTok] << " matches "
1460  << "cmd '" << strCmdName << "', "
1461  << "form " << form.getIndex() << ", "
1462  << "arg " << argdef.getIndex() << " "
1463  << "definition."
1464  << eoe;
1465 
1466  argv.push_back(argdef.convert(tokens[iTok].value(), m_bIgnoreCase));
1467 
1468  // don't decay perfection
1469  if( fWeight == 1.0 )
1470  {
1471  fFitness += fWeight;
1472  }
1473  else
1474  {
1475  fFitness += fWeight * fDecay;
1476  }
1477 
1478  fDecay *= 0.9;
1479 
1480  ++iTok;
1481  }
1482 
1483  //
1484  // Bad match, but argument is optional, and there are more optionals.
1485  //
1486  else if( argdef.isOptional() && (iArg < argcForm-1) )
1487  {
1488  rc = AOk;
1489  }
1490 
1491  //
1492  // Bad match.
1493  //
1494  else
1495  {
1496  fFitness = 0.0;
1497  }
1498  }
1499 
1500  // normalize fitness
1501  fFitness /= (double)argcToks;
1502 
1503  return rc;
1504 }
floating point number (double)
Definition: CmdArgDef.h:104
int numOfRequiredArgs() const
Get the total number of required arguments.
Definition: CmdFormDef.h:209
double match(const std::string &strArg, const bool bIgnoreCase=false) const
Match argument string against argument definition pattern.
Definition: CmdArgDef.cxx:326
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
std::string constructLiteralList(const std::string sep=" ") const
Construct literal list string.
Definition: CmdArgDef.cxx:256
undefined argument type
Definition: CmdArgDef.h:97
Command argument compiled definition class.
Definition: CmdArgDef.h:89
int getParentCmdUid() const
Get parent command&#39;s unique id.
Definition: CmdFormDef.h:142
const int EError
general, unspecified error
Definition: CmdCore.h:99
static const std::string lookupArgSymbol(const CmdArgDef::ArgType eType)
Look up argument symbol, given argument type.
Definition: CmdArgDef.cxx:587
int getIndex() const
Get forms&#39;s index.
Definition: CmdFormDef.h:152
CmdExtArg convert(const std::string &strArg, const bool bIgnoreCase=false) const
Convert argument string to type.
Definition: CmdArgDef.cxx:482
LogBook & eoe(LogBook &log)
LogBook end-of-entry stream manipulator.
Definition: LogBook.cxx:926
const int EBadSyntax
bad syntax
Definition: CmdCore.h:104
const int AOk
(0) A-Ok, no error, success, good
Definition: CmdCore.h:93
bool isOptional() const
Test if argument is an optional argument.
Definition: CmdArgDef.h:299
identifier (C conforming)
Definition: CmdArgDef.h:101
ArgType getType() const
Get argument&#39;s type.
Definition: CmdArgDef.h:214
std::string constructRangeList(const std::string sep=",") const
Construct ranges string.
Definition: CmdArgDef.cxx:270
const RangeVec & getRanges() const
Get numeric range values.
Definition: CmdArgDef.h:243
bool m_bIgnoreCase
do [not] ignore case on commands
Definition: CommandLine.h:1188
any (quoted) character sequence
Definition: CmdArgDef.h:100
int getIndex() const
Get argument&#39;s command line index.
Definition: CmdArgDef.h:194
const std::string & getRegEx() const
Get regular expression value.
Definition: CmdArgDef.h:253
const CmdArgDef & at(const int nIndex) const
Get form&#39;s argument at index.
Definition: CmdFormDef.cxx:176
CmdDefMap m_cmdDefs
map of added command definitions
Definition: CommandLine.h:1191
any non-whitespace contiguous char sequence
Definition: CmdArgDef.h:99
int numOfArgs() const
Get the total number of arguments.
Definition: CmdFormDef.h:195
int CommandLine::numOfArgs ( int  uid,
int  iform 
) const

Get the total number of arguments.

The first argument (argv0) is the command.

Parameters
uidMatched command unique id.
iformMatched command form index.
Returns
Number of arguments.

Definition at line 1542 of file CommandLine.cxx.

References rnr::cmd::CmdDef::at(), at(), and rnr::cmd::CmdFormDef::numOfArgs().

Referenced by numOfArgs().

1543 {
1544  return at(uid).at(iform).numOfArgs();
1545 }
const CmdFormDef & at(const int nIndex) const
Get command form at index.
Definition: CmdDef.cxx:175
const CmdDef & at(const int uid) const
Get the command definition with the unique id.
int numOfArgs() const
Get the total number of arguments.
Definition: CmdFormDef.h:195
int CommandLine::numOfArgs ( const CmdExtArg arg) const

Get the total number of arguments of matched command.

The extended argument contains matched command context.

Parameters
argExtended argument.
Returns
Number of arguments.

Definition at line 1547 of file CommandLine.cxx.

References at(), rnr::cmd::CmdExtArg::formIndex(), numOfArgs(), and rnr::cmd::CmdExtArg::uid().

1548 {
1549  return at(arg.uid()).at(arg.formIndex()).numOfArgs();
1550 }
int formIndex() const
Get the argument&#39;s associated parsed form definition index.
Definition: CmdExtArg.h:165
int numOfArgs(int uid, int iform) const
Get the total number of arguments.
int uid() const
Get the argument&#39;s associated parsed command unique id.
Definition: CmdExtArg.h:158
const CmdDef & at(const int uid) const
Get the command definition with the unique id.
int rnr::cmd::CommandLine::numOfCmds ( ) const
inline

Get the total number of added commands.

Returns
Number of commands.

Definition at line 1108 of file CommandLine.h.

Referenced by c14n(), compile(), execTCompile(), execTPrint(), and readCommand().

1109  {
1110  return (int)m_cmdDefs.size();
1111  }
CmdDefMap m_cmdDefs
map of added command definitions
Definition: CommandLine.h:1191
int CommandLine::numOfOptionalArgs ( int  uid,
int  iform 
) const

Get the total number of optional arguments.

Optional arguments start at argument index numOfRequiredArgs().

Parameters
uidMatched command unique id.
iformMatched command form index.
Returns
Number of optional arguments.

Definition at line 1562 of file CommandLine.cxx.

References rnr::cmd::CmdDef::at(), at(), and rnr::cmd::CmdFormDef::numOfOptionalArgs().

Referenced by numOfOptionalArgs().

1563 {
1564  return at(uid).at(iform).numOfOptionalArgs();
1565 }
int numOfOptionalArgs() const
Get the total number of optional arguments.
Definition: CmdFormDef.h:221
const CmdFormDef & at(const int nIndex) const
Get command form at index.
Definition: CmdDef.cxx:175
const CmdDef & at(const int uid) const
Get the command definition with the unique id.
int CommandLine::numOfOptionalArgs ( const CmdExtArg arg) const

Get the total number of arguments of matched command.

The extended argument contains matched command context.

Parameters
argExtended argument.
Returns
Number of optional arguments.

Definition at line 1567 of file CommandLine.cxx.

References at(), rnr::cmd::CmdExtArg::formIndex(), numOfOptionalArgs(), and rnr::cmd::CmdExtArg::uid().

1568 {
1569  return at(arg.uid()).at(arg.formIndex()).numOfOptionalArgs();
1570 }
int formIndex() const
Get the argument&#39;s associated parsed form definition index.
Definition: CmdExtArg.h:165
int uid() const
Get the argument&#39;s associated parsed command unique id.
Definition: CmdExtArg.h:158
const CmdDef & at(const int uid) const
Get the command definition with the unique id.
int numOfOptionalArgs(int uid, int iform) const
Get the total number of optional arguments.
int CommandLine::numOfRequiredArgs ( int  uid,
int  iform 
) const

Get the total number of required arguments.

The required number includes the command argv0.

Required arguments start at argument index 0.

Parameters
uidMatched command unique id.
iformMatched command form index.
Returns
Number of required arguments.

Definition at line 1552 of file CommandLine.cxx.

References rnr::cmd::CmdDef::at(), at(), and rnr::cmd::CmdFormDef::numOfRequiredArgs().

Referenced by checkCmd(), and numOfRequiredArgs().

1553 {
1554  return at(uid).at(iform).numOfRequiredArgs();
1555 }
int numOfRequiredArgs() const
Get the total number of required arguments.
Definition: CmdFormDef.h:209
const CmdFormDef & at(const int nIndex) const
Get command form at index.
Definition: CmdDef.cxx:175
const CmdDef & at(const int uid) const
Get the command definition with the unique id.
int CommandLine::numOfRequiredArgs ( const CmdExtArg arg) const

Get the total number of required arguments of matched command.

The extended argument contains matched command context.

The required number includes the command argv0.

Required arguments start at argument index 0.

Parameters
argExtended argument.
Returns
Number of required arguments.

Definition at line 1557 of file CommandLine.cxx.

References at(), rnr::cmd::CmdExtArg::formIndex(), numOfRequiredArgs(), and rnr::cmd::CmdExtArg::uid().

1558 {
1559  return at(arg.uid()).at(arg.formIndex()).numOfRequiredArgs();
1560 }
int formIndex() const
Get the argument&#39;s associated parsed form definition index.
Definition: CmdExtArg.h:165
int uid() const
Get the argument&#39;s associated parsed command unique id.
Definition: CmdExtArg.h:158
const CmdDef & at(const int uid) const
Get the command definition with the unique id.
int numOfRequiredArgs(int uid, int iform) const
Get the total number of required arguments.
bool rnr::cmd::CommandLine::ok ( ) const
inline

Test if command-line interface is ok to continue.

Returns
Returns true or false.

Definition at line 481 of file CommandLine.h.

References rnr::cmd::DataSectNsCore.

Referenced by run().

482  {
483  return !((DataSectCore*)m_dataSects.at(DataSectNsCore).data())->m_bQuit;
484  }
const char *const DataSectNsCore
Reserved command line data section namespaces.
Definition: CmdCore.h:141
DataSectMap m_dataSects
data sections
Definition: CommandLine.h:1196
const CmdDef& rnr::cmd::CommandLine::operator[] ( const int  uid) const

Index operator.

Get the command definition with the unique id.

Parameters
uidCommand unique id.
Returns
Command definition reference.
const CmdDef& rnr::cmd::CommandLine::operator[] ( const std::string &  strName) const

Index operator.

Get the command definition with the unique id.

Parameters
strNameCommand name.
Returns
Command definition reference.
bool CommandLine::parseArg ( CmdDef cmddef,
CmdFormDef form,
const TokenVec tokens,
size_t &  pos 
)
protected

Parse argument syntax.

Syntax:
<arg> ::= <xor-list-arg>
| <variable-arg>
| <literal-arg>
Parameters
[in,out]cmddefCommand definition.
[in,out]formCommand form definition.
[in]tokensLexical tokens generated from the syntax usage.
[in,out]posThe parse cursor position.
See also
parseSyntax().
Returns
Returns true on a successful parse, false otherwise.

Definition at line 2605 of file CommandLine.cxx.

References rnr::eoe(), getErrorStr(), LOGERROR_STREAM, m_log, rnr::str::okstr(), parseLiteralArg(), parseVariableArg(), parseXorListArg(), and peekEq().

Referenced by parseOptionalArgList(), and parseRequiredArgList().

2609 {
2610  bool bOk;
2611 
2612  CL_DBG_PARSE_CALL_IN(cmddef, form, tokens, pos, endl);
2613 
2614  if( pos < tokens.size() )
2615  {
2616  if( peekEq("{", tokens[pos]) )
2617  {
2618  bOk = parseXorListArg(cmddef, form, tokens, pos);
2619  }
2620  else if( peekEq("<", tokens[pos]) )
2621  {
2622  bOk = parseVariableArg(cmddef, form, tokens, pos);
2623  }
2624  else
2625  {
2626  bOk = parseLiteralArg(cmddef, form, tokens, pos);
2627  }
2628  }
2629  else
2630  {
2631  m_log << labelSyntax << "Command argument not found." << eoe;
2633  bOk = false;
2634  }
2635 
2636  CL_DBG_CALL_OUT_NL(okstr(bOk) << ", pos=" << pos);
2637 
2638  return bOk;
2639 }
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
bool peekEq(const std::string strCmp, const Token &token) const
Peek if token is equal to string.
Definition: CommandLine.h:1789
bool parseVariableArg(CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos)
Parse variable argument syntax.
LogBook & eoe(LogBook &log)
LogBook end-of-entry stream manipulator.
Definition: LogBook.cxx:926
#define LOGERROR_STREAM(args)
Error stream logging.
Definition: LogStream.h:167
std::string okstr(bool b)
Convert boolean to "ok" or "not-ok".
Definition: StringTheory.h:98
bool parseLiteralArg(CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos)
Parse literal, fixed-valued argument syntax.
bool parseXorListArg(CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos)
Parse mutually exclusive argument values syntax.
const std::string & getErrorStr() const
Get the most recent error.
bool CommandLine::parseArgv0 ( CmdDef cmddef,
CmdFormDef form,
const TokenVec tokens,
size_t &  pos 
)
protected

Parse argument 0 (command name) syntax.

Argv0 is a special argument that defines the command name. Only literal and variable arguments types are valid.

Syntax:
<argv0> ::= <literal-arg>
| <variable-arg>
Parameters
[in,out]cmddefCommand definition.
[in,out]formCommand form definition.
[in]tokensLexical tokens generated from the syntax usage.
[in,out]posThe parse cursor position.
See also
parseSyntax().
Returns
Returns true on a successful parse, false otherwise.

Definition at line 2470 of file CommandLine.cxx.

References rnr::cmd::CmdArgDef::ArgTypeLiteral, rnr::eoe(), rnr::cmd::CmdArgDef::FlagCommand, getErrorStr(), rnr::cmd::CmdFormDef::getIndex(), rnr::cmd::CmdDef::getName(), rnr::cmd::CmdArgDef::getName(), rnr::cmd::CmdArgDef::getType(), rnr::cmd::CmdFormDef::lastArg(), rnr::cmd::CmdArgDef::literalAt(), LOGERROR_STREAM, m_log, rnr::cmd::CmdFormDef::m_nArgcReq, rnr::str::okstr(), rnr::cmd::CmdArgDef::orFlags(), parseLiteralArg(), parseVariableArg(), peekEq(), and rnr::cmd::CmdDef::setName().

Referenced by parseSyntax().

2474 {
2475  bool bOk;
2476  string strName;
2477 
2478  CL_DBG_PARSE_CALL_IN(cmddef, form, tokens, pos, endl);
2479 
2480  if( pos < tokens.size() )
2481  {
2482  if( peekEq("<", tokens[pos]) )
2483  {
2484  bOk = parseVariableArg(cmddef, form, tokens, pos);
2485  }
2486  else
2487  {
2488  bOk = parseLiteralArg(cmddef, form, tokens, pos);
2489  }
2490  }
2491  else
2492  {
2493  m_log << labelSyntax << "Command argument not found in form "
2494  << form.getIndex() << "."
2495  << eoe;
2497  bOk = false;
2498  }
2499 
2500  if( bOk )
2501  {
2502  form.m_nArgcReq++;
2503 
2505 
2506  // set command's name
2507  if( form.lastArg().getType() == CmdArgDef::ArgTypeLiteral )
2508  {
2509  // literals are anonymous, use the literal itself
2510  strName = form.lastArg().literalAt(0);
2511  }
2512  else
2513  {
2514  // variables have required names
2515  strName = form.lastArg().getName();
2516  }
2517 
2518  // assign command name
2519  if( cmddef.getName().empty() )
2520  {
2521  cmddef.setName(strName);
2522  }
2523  // all forms must have the same command name
2524  else if( cmddef.getName() != strName )
2525  {
2526  m_log << labelSyntax << "Expected command name '" << cmddef.getName()
2527  << "', but found '" << strName << "' in form " << form.getIndex()
2528  << "."
2529  << eoe;
2531  bOk = false;
2532  }
2533  }
2534 
2535  CL_DBG_CALL_OUT_NL(okstr(bOk) << ", pos=" << pos);
2536 
2537  return bOk;
2538 }
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
bool peekEq(const std::string strCmp, const Token &token) const
Peek if token is equal to string.
Definition: CommandLine.h:1789
void orFlags(const unsigned uFlags)
Or flags into argment modifier flags.
Definition: CmdArgDef.cxx:251
const std::string & literalAt(const int nIndex) const
Get literal value at index.
Definition: CmdArgDef.cxx:205
int getIndex() const
Get forms&#39;s index.
Definition: CmdFormDef.h:152
bool parseVariableArg(CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos)
Parse variable argument syntax.
LogBook & eoe(LogBook &log)
LogBook end-of-entry stream manipulator.
Definition: LogBook.cxx:926
CmdArgDef & lastArg()
Get the last pushed argument.
Definition: CmdFormDef.cxx:200
argument is the command
Definition: CmdArgDef.h:114
#define LOGERROR_STREAM(args)
Error stream logging.
Definition: LogStream.h:167
void setName(const std::string &strName)
Set command&#39;s name.
Definition: CmdDef.cxx:147
const std::string & getName() const
Return command&#39;s name.
Definition: CmdDef.h:144
ArgType getType() const
Get argument&#39;s type.
Definition: CmdArgDef.h:214
std::string okstr(bool b)
Convert boolean to "ok" or "not-ok".
Definition: StringTheory.h:98
const std::string & getName() const
Get argument&#39;s name.
Definition: CmdArgDef.h:204
bool parseLiteralArg(CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos)
Parse literal, fixed-valued argument syntax.
int m_nArgcReq
number of required arguments
Definition: CmdFormDef.h:253
const std::string & getErrorStr() const
Get the most recent error.
bool CommandLine::parseIdentifier ( CmdDef cmddef,
CmdFormDef form,
const TokenVec tokens,
size_t &  pos,
std::string &  strIdent 
)
protected

Parse identifier.

Syntax:
<identifier> ::= ALPHA {ALPHANUMERIC}*
| '_' {ALPHANUMERIC}*
Parameters
[in,out]cmddefCommand definition.
[in,out]formCommand form definition.
[in]tokensLexical tokens generated from syntax usage.
[in,out]posThe parse cursor position.
See also
parseSyntax().
Parameters
[out]strIdentIdentity string.
Returns
Returns true on a successful parse, false otherwise.

Definition at line 2810 of file CommandLine.cxx.

References rnr::eoe(), getErrorStr(), LOGERROR_STREAM, m_log, rnr::str::okstr(), and tokIdentifier().

Referenced by parseVariableArg().

2815 {
2816  bool bOk;
2817 
2818  CL_DBG_PARSE_CALL_IN(cmddef, form, tokens, pos, endl);
2819 
2820  strIdent.clear();
2821 
2822  if( pos < tokens.size() )
2823  {
2824  strIdent = tokens[pos].value();
2825  bOk = tokIdentifier(tokens, pos);
2826  }
2827  else
2828  {
2829  m_log << labelSyntax << "No identifier found." << eoe;
2831  bOk = false;
2832  }
2833 
2834  CL_DBG_CALL_OUT_NL(okstr(bOk) << ", identifier='" << strIdent
2835  << "', pos=" << pos);
2836 
2837  return bOk;
2838 }
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
bool tokIdentifier(const TokenVec &tokens, size_t &pos)
Test if string has valid identifier syntax.
LogBook & eoe(LogBook &log)
LogBook end-of-entry stream manipulator.
Definition: LogBook.cxx:926
#define LOGERROR_STREAM(args)
Error stream logging.
Definition: LogStream.h:167
std::string okstr(bool b)
Convert boolean to "ok" or "not-ok".
Definition: StringTheory.h:98
const std::string & getErrorStr() const
Get the most recent error.
bool CommandLine::parseLiteralArg ( CmdDef cmddef,
CmdFormDef form,
const TokenVec tokens,
size_t &  pos 
)
protected

Parse literal, fixed-valued argument syntax.

A CmdArgDef object is added to the CmdDef

Syntax:
<literal-arg> ::= <literal>
Parameters
[in,out]cmddefCommand definition.
[in,out]formCommand form definition.
[in]tokensLexical tokens generated from the syntax usage.
[in,out]posThe parse cursor position.
See also
parseSyntax().
Returns
Returns true on a successful parse, false otherwise.

Definition at line 2729 of file CommandLine.cxx.

References rnr::cmd::CmdArgDef::addLiteralValue(), rnr::cmd::CmdArgDef::ArgTypeLiteral, rnr::cmd::CmdFormDef::lastArg(), rnr::cmd::CmdFormDef::numOfArgs(), rnr::str::okstr(), parseLiteralValue(), rnr::cmd::CmdFormDef::pushArg(), rnr::cmd::CmdArgDef::setName(), and rnr::cmd::CmdArgDef::setType().

Referenced by parseArg(), and parseArgv0().

2733 {
2734  bool bOk;
2735  CmdArgDef argdef;
2736  string strValue;
2737 
2738  CL_DBG_PARSE_CALL_IN(cmddef, form, tokens, pos, endl);
2739 
2740  form.pushArg(argdef);
2741 
2742  bOk = parseLiteralValue(cmddef, form, tokens, pos, strValue);
2743 
2744  if( bOk )
2745  {
2746  stringstream ss;
2747  int n = form.numOfArgs() - 1;
2748 
2749  ss << "_" << n;
2750 
2751  form.lastArg().setName(ss.str());
2753  form.lastArg().addLiteralValue(strValue);
2754  }
2755 
2756  CL_DBG_CALL_OUT_NL(okstr(bOk) << ", pos=" << pos);
2757 
2758  return bOk;
2759 }
void pushArg(CmdArgDef &argdef)
Push argument to end of argument list.
Definition: CmdFormDef.cxx:167
Command argument compiled definition class.
Definition: CmdArgDef.h:89
void addLiteralValue(const std::string &strValue)
Add literal value to list of argument values.
Definition: CmdArgDef.cxx:200
void setType(const ArgType eType)
Set argument&#39;s type.
Definition: CmdArgDef.cxx:195
CmdArgDef & lastArg()
Get the last pushed argument.
Definition: CmdFormDef.cxx:200
std::string okstr(bool b)
Convert boolean to "ok" or "not-ok".
Definition: StringTheory.h:98
void setName(const std::string &strName)
Set argument&#39;s name.
Definition: CmdArgDef.cxx:190
bool parseLiteralValue(CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos, std::string &strValue)
Parse literal value.
int numOfArgs() const
Get the total number of arguments.
Definition: CmdFormDef.h:195
bool CommandLine::parseLiteralValue ( CmdDef cmddef,
CmdFormDef form,
const TokenVec tokens,
size_t &  pos,
std::string &  strValue 
)
protected

Parse literal value.

Syntax:
<literal> ::= {NON_SPECIAL_CHAR}+
Parameters
[in,out]cmddefCommand definition.
[in,out]formCommand form definition.
[in]tokensLexical tokens generated from syntax usage.
[in,out]posThe parse cursor position.
See also
parseSyntax().
Parameters
[out]strValueValue string.
Returns
Returns true on a successful parse, false otherwise.

Definition at line 3079 of file CommandLine.cxx.

References rnr::eoe(), getErrorStr(), LOGERROR_STREAM, m_log, and rnr::str::okstr().

Referenced by parseLiteralArg(), and parseXorList().

3084 {
3085  bool bOk;
3086 
3087  CL_DBG_PARSE_CALL_IN(cmddef, form, tokens, pos, " ");
3088 
3089  strValue.clear();
3090 
3091  if( pos < tokens.size() )
3092  {
3093  strValue = tokens[pos++].value();
3094  bOk = true;
3095  }
3096  else
3097  {
3098  m_log << labelSyntax << "Literal value not found." << eoe;
3100  bOk = false;
3101  }
3102 
3103  CL_DBG_CALL_OUT_IL(okstr(bOk) << ", value='" << strValue << "', "
3104  << "pos=" << pos);
3105 
3106  return bOk;
3107 }
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
LogBook & eoe(LogBook &log)
LogBook end-of-entry stream manipulator.
Definition: LogBook.cxx:926
#define LOGERROR_STREAM(args)
Error stream logging.
Definition: LogStream.h:167
std::string okstr(bool b)
Convert boolean to "ok" or "not-ok".
Definition: StringTheory.h:98
const std::string & getErrorStr() const
Get the most recent error.
bool CommandLine::parseOptionalArgList ( CmdDef cmddef,
CmdFormDef form,
const TokenVec tokens,
size_t &  pos 
)
protected

Parse optional argument list syntax.

Syntax:
<optional-arg-list> ::= '[' <arg> ']'
| <optional-arg-list> '[' <arg> ']'
Parameters
[in,out]cmddefCommand definition.
[in,out]formCommand form definition.
[in]tokensLexical tokens generated from the syntax usage.
[in,out]posThe parse cursor position.
See also
parseSyntax().
Returns
Returns true on a successful parse, false otherwise.

Definition at line 2569 of file CommandLine.cxx.

References rnr::cmd::CmdArgDef::FlagOptional, rnr::cmd::CmdFormDef::lastArg(), rnr::cmd::CmdFormDef::m_nArgcOpt, rnr::str::okstr(), rnr::cmd::CmdArgDef::orFlags(), parseArg(), peekEq(), and tokEq().

Referenced by parseSyntax().

2573 {
2574  bool bOk = true;
2575 
2576  CL_DBG_PARSE_CALL_IN(cmddef, form, tokens, pos, endl);
2577 
2578  while( bOk && (pos < tokens.size()) )
2579  {
2580  // peek if start an optional arguments
2581  if( !peekEq("[", tokens[pos]) )
2582  {
2583  break;
2584  }
2585 
2586  // "[ argument ]"
2587  if( tokEq("[", tokens, pos) &&
2588  parseArg(cmddef, form, tokens, pos) &&
2589  tokEq("]", tokens, pos) )
2590  {
2592  form.m_nArgcOpt++;
2593  }
2594  else
2595  {
2596  bOk = false;
2597  }
2598  }
2599 
2600  CL_DBG_CALL_OUT_NL(okstr(bOk) << ", pos=" << pos);
2601 
2602  return bOk;
2603 }
bool peekEq(const std::string strCmp, const Token &token) const
Peek if token is equal to string.
Definition: CommandLine.h:1789
argument is optional
Definition: CmdArgDef.h:115
void orFlags(const unsigned uFlags)
Or flags into argment modifier flags.
Definition: CmdArgDef.cxx:251
CmdArgDef & lastArg()
Get the last pushed argument.
Definition: CmdFormDef.cxx:200
std::string okstr(bool b)
Convert boolean to "ok" or "not-ok".
Definition: StringTheory.h:98
bool tokEq(const std::string strCmp, const TokenVec &tokens, size_t &pos)
Test if token at position is equal to string.
bool parseArg(CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos)
Parse argument syntax.
int m_nArgcOpt
number of optional arguments
Definition: CmdFormDef.h:254
bool CommandLine::parseRequiredArgList ( CmdDef cmddef,
CmdFormDef form,
const TokenVec tokens,
size_t &  pos 
)
protected

Parse required argument list syntax.

Syntax:
<required-arg-list> ::= <arg>
| <required-arg-list> <arg>
Parameters
[in,out]cmddefCommand definition.
[in,out]formCommand form definition.
[in]tokensLexical tokens generated from the syntax usage.
[in,out]posThe parse cursor position.
See also
parseSyntax().
Returns
Returns true on a successful parse, false otherwise.

Definition at line 2540 of file CommandLine.cxx.

References rnr::cmd::CmdFormDef::m_nArgcReq, rnr::str::okstr(), parseArg(), and peekEq().

Referenced by parseSyntax().

2544 {
2545  bool bOk = true;
2546 
2547  CL_DBG_PARSE_CALL_IN(cmddef, form, tokens, pos, endl);
2548 
2549  while( bOk && (pos < tokens.size()) )
2550  {
2551  // peek if start of optional arguments
2552  if( peekEq("[", tokens[pos]) )
2553  {
2554  break;
2555  }
2556 
2557  // required argument
2558  else if( (bOk = parseArg(cmddef, form, tokens, pos)) )
2559  {
2560  form.m_nArgcReq++;
2561  }
2562  }
2563 
2564  CL_DBG_CALL_OUT_NL(okstr(bOk) << ", pos=" << pos);
2565 
2566  return bOk;
2567 }
bool peekEq(const std::string strCmp, const Token &token) const
Peek if token is equal to string.
Definition: CommandLine.h:1789
std::string okstr(bool b)
Convert boolean to "ok" or "not-ok".
Definition: StringTheory.h:98
int m_nArgcReq
number of required arguments
Definition: CmdFormDef.h:253
bool parseArg(CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos)
Parse argument syntax.
int CommandLine::parseSyntax ( CmdDef cmddef,
CmdFormDef form,
const TokenVec tokens 
)
protectedvirtual

Parse command syntax.

The parsed, generated internal data are used for readline tab completion, input - command pattern matching, and first-level validation.

The parseSyntax() function [in]directly calls the CommandLine::parse family of member functions. Each function takes, at a minimum, four parameters:

Parameter Description
cmddef Definition of an added command. It may be modified.
form Definition of a command form. It may be modified.
tokens Lexical tokens generated from the extended usage syntax.
pos The parse cursor position. On input, it specifies
^ the starting position in the tokens vector. On a
^ succesful parse, the cursor position is advanced
^ to the first token after the relevant syntax block.
Syntax:
<command> ::= <argv0> [<required-arg-list>] [<optional-arg-list>]
Parameters
[in,out]cmddefCommand definition.
[in,out]formCommand form definition.
[in]tokensLexical tokens generated from the syntax usage.
Returns
On success, AOk(0) is returned. On error, a CommandLine error code (< 0) is returned. See getErroStr() and backtrace() to retrieve or print error(s).

Definition at line 2398 of file CommandLine.cxx.

References rnr::cmd::AOk, rnr::cmd::EBadSyntax, rnr::eoe(), getErrorStr(), rnr::cmd::CmdFormDef::getIndex(), rnr::cmd::CmdDef::getName(), rnr::cmd::CmdFormDef::getSyntax(), rnr::cmd::CmdDef::getUid(), LOGDIAG2_STREAM, LOGERROR_STREAM, m_log, rnr::cmd::CmdFormDef::numOfArgs(), rnr::str::okstr(), parseArgv0(), parseOptionalArgList(), and parseRequiredArgList().

Referenced by compile().

2401 {
2402  size_t tokcnt = tokens.size();
2403  size_t pos = 0;
2404  bool bOk = true;
2405  int rc;
2406 
2407  CL_DBG_PARSE_CALL_IN(cmddef, form, tokens, 0, endl);
2408 
2409  m_log << labelParse
2410  << "cmddef " << cmddef.getUid() << ", "
2411  << "form " << form.getIndex() << ": "
2412  << form.getSyntax()
2413  << eoe;
2414 
2415  // command
2416  if( !parseArgv0(cmddef, form, tokens, pos) )
2417  {
2418  m_log << labelFail << "Parssing special argv0." << eoe;
2419  bOk = false;
2420  }
2421 
2422  // required argmuents - may be none
2423  else if( !parseRequiredArgList(cmddef, form, tokens, pos) )
2424  {
2425  m_log << labelFail << "Parsing required argument list." << eoe;
2426  bOk = false;
2427  }
2428 
2429  // optional arguments - may be none
2430  else if( !parseOptionalArgList(cmddef, form, tokens, pos) )
2431  {
2432  m_log << labelFail << "Parsing optional argument list." << eoe;
2433  bOk = false;
2434  }
2435 
2436  // final checks
2437  else if( pos < tokcnt )
2438  {
2439  m_log << labelFail
2440  << "Extraneous tokens found after optional arguments."
2441  << eoe;
2442  bOk = false;
2443  }
2444 
2445  // all good
2446  if( bOk )
2447  {
2448  m_log << labelParse << "Ok" << eoe;
2449  LOGDIAG2_STREAM("Command("
2450  << "uid=" << cmddef.getUid() << ", "
2451  << "name=" << cmddef.getName() << ", "
2452  << "form=" << form.getIndex() << ", "
2453  << "argc=" << form.numOfArgs() << ") "
2454  << "successfully parsed.");
2455  rc = AOk;
2456  }
2457 
2458  // not so good - log error
2459  else
2460  {
2462  rc = EBadSyntax;
2463  }
2464 
2465  CL_DBG_CALL_OUT_NL("rc=" << rc << ", " << okstr(bOk) << ", pos=" << pos);
2466 
2467  return rc;
2468 }
#define LOGDIAG2_STREAM(args)
Diagnostic level 2 stream logging.
Definition: LogStream.h:128
int getUid() const
Get command&#39;s unique id.
Definition: CmdDef.h:134
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
bool parseArgv0(CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos)
Parse argument 0 (command name) syntax.
int getIndex() const
Get forms&#39;s index.
Definition: CmdFormDef.h:152
bool parseOptionalArgList(CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos)
Parse optional argument list syntax.
bool parseRequiredArgList(CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos)
Parse required argument list syntax.
LogBook & eoe(LogBook &log)
LogBook end-of-entry stream manipulator.
Definition: LogBook.cxx:926
const int EBadSyntax
bad syntax
Definition: CmdCore.h:104
const int AOk
(0) A-Ok, no error, success, good
Definition: CmdCore.h:93
#define LOGERROR_STREAM(args)
Error stream logging.
Definition: LogStream.h:167
const std::string & getName() const
Return command&#39;s name.
Definition: CmdDef.h:144
std::string okstr(bool b)
Convert boolean to "ok" or "not-ok".
Definition: StringTheory.h:98
std::string getSyntax() const
Get form&#39;s extended usage syntax.
Definition: CmdFormDef.h:160
const std::string & getErrorStr() const
Get the most recent error.
int numOfArgs() const
Get the total number of arguments.
Definition: CmdFormDef.h:195
bool CommandLine::parseVariableArg ( CmdDef cmddef,
CmdFormDef form,
const TokenVec tokens,
size_t &  pos 
)
protected

Parse variable argument syntax.

A CmdArgDef object is added to the CmdDef

Syntax:
<variable-arg> ::= '<' <identifier> '>'
| '<' <identifier> ':' <var-modifier> '>'
Parameters
[in,out]cmddefCommand definition.
[in,out]formCommand form definition.
[in]tokensLexical tokens generated from the syntax usage.
[in,out]posThe parse cursor position.
See also
parseSyntax().
Returns
Returns true on a successful parse, false otherwise.

Definition at line 2680 of file CommandLine.cxx.

References rnr::cmd::CmdArgDef::ArgTypeWord, rnr::cmd::CmdFormDef::lastArg(), rnr::str::okstr(), parseIdentifier(), parseVarMod(), peekEq(), rnr::cmd::CmdFormDef::pushArg(), rnr::cmd::CmdArgDef::setName(), rnr::cmd::CmdArgDef::setRanges(), rnr::cmd::CmdArgDef::setRegEx(), rnr::cmd::CmdArgDef::setType(), and tokEq().

Referenced by parseArg(), and parseArgv0().

2684 {
2685  bool bOk;
2686  CmdArgDef argdef;
2687  string strName;
2688  CmdArgDef::ArgType eType;
2689  CmdArgDef::RangeVec ranges;
2690  RegEx re;
2691 
2692  CL_DBG_PARSE_CALL_IN(cmddef, form, tokens, pos, endl);
2693 
2694  form.pushArg(argdef);
2695 
2696  bOk = tokEq("<", tokens, pos) &&
2697  parseIdentifier(cmddef, form, tokens, pos, strName);
2698 
2699  if( bOk )
2700  {
2701  // variable modifier
2702  if( peekEq(":", tokens[pos]) )
2703  {
2704  bOk = tokEq(":", tokens, pos) &&
2705  parseVarMod(cmddef, form, tokens, pos, eType, ranges, re);
2706  }
2707  // default
2708  else
2709  {
2710  eType = CmdArgDef::ArgTypeWord;
2711  }
2712  }
2713 
2714  bOk = bOk && tokEq(">", tokens, pos);
2715 
2716  if( bOk )
2717  {
2718  form.lastArg().setName(strName);
2719  form.lastArg().setType(eType);
2720  form.lastArg().setRanges(ranges);
2721  form.lastArg().setRegEx(re);
2722  }
2723 
2724  CL_DBG_CALL_OUT_NL(okstr(bOk) << ", pos=" << pos);
2725 
2726  return bOk;
2727 }
void setRanges(const RangeVec &ranges)
Set numeric range values.
Definition: CmdArgDef.cxx:217
bool peekEq(const std::string strCmp, const Token &token) const
Peek if token is equal to string.
Definition: CommandLine.h:1789
void pushArg(CmdArgDef &argdef)
Push argument to end of argument list.
Definition: CmdFormDef.cxx:167
Command argument compiled definition class.
Definition: CmdArgDef.h:89
Regular Express Class.
Definition: RegEx.h:84
void setType(const ArgType eType)
Set argument&#39;s type.
Definition: CmdArgDef.cxx:195
bool parseVarMod(CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos, CmdArgDef::ArgType &eType, CmdArgDef::RangeVec &ranges, RegEx &re)
Parse variable modifier.
ArgType
Argument type enumeration.
Definition: CmdArgDef.h:95
CmdArgDef & lastArg()
Get the last pushed argument.
Definition: CmdFormDef.cxx:200
void setRegEx(const RegEx &re)
Set regular expression value.
Definition: CmdArgDef.cxx:246
std::string okstr(bool b)
Convert boolean to "ok" or "not-ok".
Definition: StringTheory.h:98
std::vector< range > RangeVec
vector of subranges
Definition: CmdArgDef.h:129
bool tokEq(const std::string strCmp, const TokenVec &tokens, size_t &pos)
Test if token at position is equal to string.
bool parseIdentifier(CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos, std::string &strIdent)
Parse identifier.
void setName(const std::string &strName)
Set argument&#39;s name.
Definition: CmdArgDef.cxx:190
any non-whitespace contiguous char sequence
Definition: CmdArgDef.h:99
bool CommandLine::parseVarMod ( CmdDef cmddef,
CmdFormDef form,
const TokenVec tokens,
size_t &  pos,
CmdArgDef::ArgType eType,
CmdArgDef::RangeVec ranges,
RegEx re 
)
protected

Parse variable modifier.

Syntax:
<var-modifier> ::= <var-type>
| <var-type> <var-paren-expr>
<var-paren-expr> ::= '(' <range-expr> ')'
| '(' <regex> ')'
Parameters
[in,out]cmddefCommand definition.
[in,out]formCommand form definition.
[in]tokensLexical tokens generated from the syntax usage.
[in,out]posThe parse cursor position.
See also
parseSyntax().
Parameters
[out]eTypeType enum.
[out]rangesVector of ranges.
[out]reRegular expression.
Returns
Returns true on a successful parse, false otherwise.

Definition at line 2840 of file CommandLine.cxx.

References rnr::cmd::CmdArgDef::ArgTypeFpn, rnr::cmd::CmdArgDef::ArgTypeInteger, rnr::cmd::CmdArgDef::ArgTypeRegEx, rnr::eoe(), getErrorStr(), LOGERROR_STREAM, rnr::cmd::CmdArgDef::lookupArgSymbol(), m_log, rnr::str::okstr(), parseVarRangeExpr(), parseVarRegExpr(), parseVarType(), peekEq(), and tokEq().

Referenced by parseVariableArg().

2847 {
2848  bool bOk;
2849 
2850  CL_DBG_PARSE_CALL_IN(cmddef, form, tokens, pos, endl);
2851 
2852  bOk = parseVarType(cmddef, form, tokens, pos, eType);
2853 
2854  if( bOk )
2855  {
2856  if( peekEq("(", tokens[pos]) )
2857  {
2858  switch( eType )
2859  {
2861  case CmdArgDef::ArgTypeFpn:
2862  bOk = tokEq("(", tokens, pos) &&
2863  parseVarRangeExpr(cmddef, form, tokens, pos, ranges) &&
2864  tokEq(")", tokens, pos);
2865  break;
2867  bOk = tokEq("(", tokens, pos) &&
2868  parseVarRegExpr(cmddef, form, tokens, pos, re) &&
2869  tokEq(")", tokens, pos);
2870  break;
2871  default:
2872  m_log << labelSyntax
2873  << "Unexpected '(' token found for argument type "
2874  << "'" << CmdArgDef::lookupArgSymbol(eType) << "'."
2875  << eoe;
2877  bOk = false;
2878  }
2879  }
2880  }
2881 
2882  CL_DBG_CALL_OUT_NL(okstr(bOk) << ", type=" << eType << ", pos=" << pos);
2883 
2884  return bOk;
2885 }
floating point number (double)
Definition: CmdArgDef.h:104
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
bool parseVarRegExpr(CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos, RegEx &re)
Parse variable regular expression.
bool peekEq(const std::string strCmp, const Token &token) const
Peek if token is equal to string.
Definition: CommandLine.h:1789
static const std::string lookupArgSymbol(const CmdArgDef::ArgType eType)
Look up argument symbol, given argument type.
Definition: CmdArgDef.cxx:587
bool parseVarRangeExpr(CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos, CmdArgDef::RangeVec &ranges)
Parse variable range expression.
LogBook & eoe(LogBook &log)
LogBook end-of-entry stream manipulator.
Definition: LogBook.cxx:926
#define LOGERROR_STREAM(args)
Error stream logging.
Definition: LogStream.h:167
std::string okstr(bool b)
Convert boolean to "ok" or "not-ok".
Definition: StringTheory.h:98
bool parseVarType(CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos, CmdArgDef::ArgType &eType)
Parse variable type.
const std::string & getErrorStr() const
Get the most recent error.
bool tokEq(const std::string strCmp, const TokenVec &tokens, size_t &pos)
Test if token at position is equal to string.
bool CommandLine::parseVarRangeExpr ( CmdDef cmddef,
CmdFormDef form,
const TokenVec tokens,
size_t &  pos,
CmdArgDef::RangeVec ranges 
)
protected

Parse variable range expression.

Syntax:
<range-expr> ::= <range>
| <range-expr> ',' <range>
<range> ::= NUMBER
| NUMBER ':' NUMBER
Parameters
[in,out]cmddefCommand definition.
[in,out]formCommand form definition.
[in]tokensLexical tokens generated from the syntax usage.
[in,out]posThe parse cursor position.
See also
parseSyntax().
Parameters
[out]rangesVector of ranges.
Returns
Returns true on a successful parse, false otherwise.

Definition at line 2929 of file CommandLine.cxx.

References rnr::eoe(), getErrorStr(), LOGERROR_STREAM, m_log, rnr::cmd::CmdArgDef::range::max, rnr::cmd::CmdArgDef::range::min, rnr::str::okstr(), rnr::str::split(), and rnr::str::todouble().

Referenced by parseVarMod().

2934 {
2935  bool bOk = true;
2936  StringVec subranges;
2937  StringVec minmax;
2938  CmdArgDef::range r;
2939 
2940  CL_DBG_PARSE_CALL_IN(cmddef, form, tokens, pos, " ");
2941 
2942  ranges.clear();
2943 
2944  if( pos < tokens.size() )
2945  {
2946  split(tokens[pos].value(), ',', subranges);
2947 
2948  for(size_t i = 0; bOk && (i < subranges.size()); ++i)
2949  {
2950  minmax.clear();
2951 
2952  split(subranges[i], ':', minmax);
2953 
2954  if( minmax.size() == 0 )
2955  {
2956  m_log << labelSyntax << "No 'min[:max]' subrange found in "
2957  << "'" << tokens[pos].value() << "'.'"
2958  << eoe;
2959  bOk = false;
2960  break;
2961  }
2962  else if( minmax.size() > 2 )
2963  {
2964  m_log << labelSyntax << "Too many 'min:max:?' subrange values found in "
2965  << "'" << tokens[pos].value() << "'.'"
2966  << eoe;
2967  bOk = false;
2968  break;
2969  }
2970 
2971  if( todouble(minmax[0], r.min) != OK )
2972  {
2973  m_log << labelSyntax << "Subrange min '" << minmax[0] << "' NaN in "
2974  << "'" << tokens[pos].value() << "'.'"
2975  << eoe;
2976  bOk = false;
2977  break;
2978  }
2979 
2980  if( minmax.size() == 2 )
2981  {
2982  if( todouble(minmax[1], r.max) != OK )
2983  {
2984  m_log << labelSyntax << "Subrange max '" << minmax[1] << "' NaN in "
2985  << "'" << tokens[pos].value() << "'.'"
2986  << eoe;
2987  bOk = false;
2988  break;
2989  }
2990  }
2991  else
2992  {
2993  r.max = r.min;
2994  }
2995 
2996  // reverse ranges are ok, just swap order
2997  if( r.max < r.min )
2998  {
2999  double tmp;
3000 
3001  r.min = tmp;
3002  r.min = r.max;
3003  r.max = r.min;
3004  }
3005 
3006  ranges.push_back(r);
3007  }
3008  }
3009 
3010  // everything is cool, but no ranges specified
3011  if( bOk && (ranges.size() == 0) )
3012  {
3013  m_log << labelSyntax << "Range expression not found." << eoe;
3014  bOk = false;
3015  }
3016 
3017  if( bOk )
3018  {
3019  ++pos; // advance token parse position
3020  }
3021  else
3022  {
3024  }
3025 
3026  CL_DBG_CALL_OUT_IL(okstr(bOk) << ", numranges=" << ranges.size()
3027  << ", pos=" << pos);
3028 
3029  return bOk;
3030 }
std::vector< std::string > StringVec
Useful types.
Definition: StringTheory.h:83
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
double min
minimum value
Definition: CmdArgDef.h:125
Number minimum and maximum (sub)range.
Definition: CmdArgDef.h:123
size_t split(const std::string &str, const char delim, StringVec &elems)
Split string.
int todouble(const std::string &str, double &val)
Convert string to a double-precision floating-point number.
LogBook & eoe(LogBook &log)
LogBook end-of-entry stream manipulator.
Definition: LogBook.cxx:926
#define LOGERROR_STREAM(args)
Error stream logging.
Definition: LogStream.h:167
std::string okstr(bool b)
Convert boolean to "ok" or "not-ok".
Definition: StringTheory.h:98
const std::string & getErrorStr() const
Get the most recent error.
double max
maximum value
Definition: CmdArgDef.h:126
bool CommandLine::parseVarRegExpr ( CmdDef cmddef,
CmdFormDef form,
const TokenVec tokens,
size_t &  pos,
RegEx re 
)
protected

Parse variable regular expression.

Syntax:
<regex> ::= REGEX
Parameters
[in,out]cmddefCommand definition.
[in,out]formCommand form definition.
[in]tokensLexical tokens generated from the syntax usage.
[in,out]posThe parse cursor position.
See also
parseSyntax().
Parameters
[out]reRegular expression.
Returns
Returns true on a successful parse, false otherwise.

Definition at line 3032 of file CommandLine.cxx.

References rnr::eoe(), rnr::RegEx::getErrorStr(), getErrorStr(), rnr::RegEx::getRegEx(), rnr::RegEx::isValid(), LOGERROR_STREAM, m_bIgnoreCase, m_log, rnr::str::okstr(), rnr::RegEx::ReFlagICase, and rnr::RegEx::setFlags().

Referenced by parseVarMod().

3037 {
3038  bool bOk;
3039 
3040  CL_DBG_PARSE_CALL_IN(cmddef, form, tokens, pos, " ");
3041 
3042  if( pos < tokens.size() )
3043  {
3044  if( m_bIgnoreCase )
3045  {
3047  }
3048 
3049  re = tokens[pos++].value();
3050 
3051  if( re.isValid() )
3052  {
3053  bOk = true;
3054  }
3055  else
3056  {
3057  m_log << labelSyntax << "Regular expression '"
3058  << "'" << re.getRegEx() << "': "
3059  << re.getErrorStr() << "."
3060  << eoe;
3062  bOk = false;
3063  }
3064  }
3065 
3066  else
3067  {
3068  m_log << labelSyntax << "Regular expression not found." << eoe;
3070  bOk = false;
3071  }
3072 
3073  CL_DBG_CALL_OUT_IL(okstr(bOk) << ", re='" << re.getRegEx() << "', pos="
3074  << pos);
3075 
3076  return bOk;
3077 }
static const int ReFlagICase
ignore case when matching
Definition: RegEx.h:107
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
const std::string & getRegEx() const
Get the pre-compiled regular expression.
Definition: RegEx.h:342
LogBook & eoe(LogBook &log)
LogBook end-of-entry stream manipulator.
Definition: LogBook.cxx:926
const std::string & getErrorStr() const
Get the last RegExs operation error string.
Definition: RegEx.h:401
#define LOGERROR_STREAM(args)
Error stream logging.
Definition: LogStream.h:167
std::string okstr(bool b)
Convert boolean to "ok" or "not-ok".
Definition: StringTheory.h:98
bool m_bIgnoreCase
do [not] ignore case on commands
Definition: CommandLine.h:1188
bool isValid() const
Test if in a valid state (i.e. compiled).
Definition: RegEx.h:354
const std::string & getErrorStr() const
Get the most recent error.
void setFlags(int nFlags)
Set new compile behavior flags.
Definition: RegEx.cxx:397
bool CommandLine::parseVarType ( CmdDef cmddef,
CmdFormDef form,
const TokenVec tokens,
size_t &  pos,
CmdArgDef::ArgType eType 
)
protected

Parse variable type.

Syntax:
<var-type> ::= word | multiword | identifier | bool |
int | fpn | re | file
Parameters
[in,out]cmddefCommand definition.
[in,out]formCommand form definition.
[in]tokensLexical tokens generated from the syntax usage.
[in,out]posThe parse cursor position.
See also
parseSyntax().
Parameters
[out]eTypeType enum.
Returns
Returns true on a successful parse, false otherwise.

Definition at line 2887 of file CommandLine.cxx.

References rnr::cmd::CmdArgDef::ArgTypeUndef, rnr::eoe(), getErrorStr(), LOGERROR_STREAM, rnr::cmd::CmdArgDef::lookupArgType(), m_log, and rnr::str::okstr().

Referenced by parseVarMod().

2892 {
2893  bool bOk;
2894 
2895  CL_DBG_PARSE_CALL_IN(cmddef, form, tokens, pos, " ");
2896 
2897  eType = CmdArgDef::ArgTypeUndef;
2898 
2899  if( pos < tokens.size() )
2900  {
2901  eType = CmdArgDef::lookupArgType(tokens[pos].value());
2902 
2903  if( eType != CmdArgDef::ArgTypeUndef )
2904  {
2905  ++pos;
2906  bOk = true;
2907  }
2908  else
2909  {
2910  m_log << labelSyntax << "Unknown variable type '" << tokens[pos].value()
2911  << "'." << eoe;
2913  bOk = false;
2914  }
2915  }
2916 
2917  else
2918  {
2919  m_log << labelSyntax << "No variable type found." << eoe;
2921  bOk = false;
2922  }
2923 
2924  CL_DBG_CALL_OUT_IL(okstr(bOk) << ", type=" << eType << ", pos=" << pos);
2925 
2926  return bOk;
2927 }
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
undefined argument type
Definition: CmdArgDef.h:97
LogBook & eoe(LogBook &log)
LogBook end-of-entry stream manipulator.
Definition: LogBook.cxx:926
#define LOGERROR_STREAM(args)
Error stream logging.
Definition: LogStream.h:167
std::string okstr(bool b)
Convert boolean to "ok" or "not-ok".
Definition: StringTheory.h:98
static CmdArgDef::ArgType lookupArgType(const std::string strSymbol)
Look up argument type, given argument type symbol.
Definition: CmdArgDef.cxx:575
const std::string & getErrorStr() const
Get the most recent error.
bool CommandLine::parseXorList ( CmdDef cmddef,
CmdFormDef form,
const TokenVec tokens,
size_t &  pos,
str::StringVec literals 
)
protected

Parse mutually exclusive list.

Syntax:
<xor-list> ::= <literal>
| <xor-list> '|' <literal>
Parameters
[in,out]cmddefCommand definition.
[in,out]formCommand form definition.
[in]tokensLexical tokens generated from syntax usage.
[in,out]posThe parse cursor position.
See also
parseSyntax().
Parameters
[out]literalsVector of literals.
Returns
Returns true on a successful parse, false otherwise.

Definition at line 2761 of file CommandLine.cxx.

References rnr::eoe(), getErrorStr(), LOGERROR_STREAM, m_log, rnr::str::okstr(), parseLiteralValue(), peekEq(), and tokEq().

Referenced by parseXorListArg().

2766 {
2767  bool bOk = true;
2768  bool more = true;
2769  string strValue;
2770 
2771  CL_DBG_PARSE_CALL_IN(cmddef, form, tokens, pos, endl);
2772 
2773  while( more && bOk && (pos < tokens.size()) )
2774  {
2775  if( peekEq("}", tokens[pos]) )
2776  {
2777  m_log << labelSyntax << "Expected literal value but found '}'." << eoe;
2779  bOk = false;
2780  }
2781 
2782  else if( (bOk = parseLiteralValue(cmddef, form, tokens, pos, strValue)) )
2783  {
2784  literals.push_back(strValue);
2785 
2786  // peek if start of another xor option
2787  if( peekEq("|", tokens[pos]) )
2788  {
2789  bOk = tokEq("|", tokens, pos);
2790  }
2791  else
2792  {
2793  more = false;
2794  }
2795  }
2796  }
2797 
2798  if( more && bOk )
2799  {
2800  m_log << labelSyntax << "No literal value found." << eoe;
2802  bOk = false;
2803  }
2804 
2805  CL_DBG_CALL_OUT_NL(okstr(bOk) << ", pos=" << pos);
2806 
2807  return bOk;
2808 }
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
bool peekEq(const std::string strCmp, const Token &token) const
Peek if token is equal to string.
Definition: CommandLine.h:1789
LogBook & eoe(LogBook &log)
LogBook end-of-entry stream manipulator.
Definition: LogBook.cxx:926
#define LOGERROR_STREAM(args)
Error stream logging.
Definition: LogStream.h:167
std::string okstr(bool b)
Convert boolean to "ok" or "not-ok".
Definition: StringTheory.h:98
const std::string & getErrorStr() const
Get the most recent error.
bool tokEq(const std::string strCmp, const TokenVec &tokens, size_t &pos)
Test if token at position is equal to string.
bool parseLiteralValue(CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos, std::string &strValue)
Parse literal value.
bool CommandLine::parseXorListArg ( CmdDef cmddef,
CmdFormDef form,
const TokenVec tokens,
size_t &  pos 
)
protected

Parse mutually exclusive argument values syntax.

A CmdArgDef object is added to the CmdDef

Syntax:
<xor-list-arg> ::= '{' <xor-list> '}'
Parameters
[in,out]cmddefCommand definition.
[in,out]formCommand form definition.
[in]tokensLexical tokens generated from the syntax usage.
[in,out]posThe parse cursor position.
See also
parseSyntax().
Returns
Returns true on a successful parse, false otherwise.

Definition at line 2641 of file CommandLine.cxx.

References rnr::cmd::CmdArgDef::addLiteralValue(), rnr::cmd::CmdArgDef::ArgTypeLiteral, rnr::cmd::CmdArgDef::FlagXorList, rnr::cmd::CmdFormDef::lastArg(), rnr::cmd::CmdFormDef::numOfArgs(), rnr::str::okstr(), rnr::cmd::CmdArgDef::orFlags(), parseXorList(), rnr::cmd::CmdFormDef::pushArg(), rnr::cmd::CmdArgDef::setName(), rnr::cmd::CmdArgDef::setType(), and tokEq().

Referenced by parseArg().

2645 {
2646  bool bOk;
2647  CmdArgDef argdef;
2648  StringVec literals;
2649 
2650  CL_DBG_PARSE_CALL_IN(cmddef, form, tokens, pos, endl);
2651 
2652  form.pushArg(argdef);
2653 
2654  bOk = tokEq("{", tokens, pos) &&
2655  parseXorList(cmddef, form, tokens, pos, literals) &&
2656  tokEq("}", tokens, pos);
2657 
2658  if( bOk )
2659  {
2660  stringstream ss;
2661  int n = form.numOfArgs() - 1;
2662 
2663  ss << "_" << n;
2664 
2665  form.lastArg().setName(ss.str());
2668 
2669  for(size_t i = 0; i < literals.size(); ++i)
2670  {
2671  form.lastArg().addLiteralValue(literals[i]);
2672  }
2673  }
2674 
2675  CL_DBG_CALL_OUT_NL(okstr(bOk) << ", pos=" << pos);
2676 
2677  return bOk;
2678 }
argument has a mutually exclusive list
Definition: CmdArgDef.h:116
std::vector< std::string > StringVec
Useful types.
Definition: StringTheory.h:83
void pushArg(CmdArgDef &argdef)
Push argument to end of argument list.
Definition: CmdFormDef.cxx:167
Command argument compiled definition class.
Definition: CmdArgDef.h:89
void addLiteralValue(const std::string &strValue)
Add literal value to list of argument values.
Definition: CmdArgDef.cxx:200
void orFlags(const unsigned uFlags)
Or flags into argment modifier flags.
Definition: CmdArgDef.cxx:251
void setType(const ArgType eType)
Set argument&#39;s type.
Definition: CmdArgDef.cxx:195
CmdArgDef & lastArg()
Get the last pushed argument.
Definition: CmdFormDef.cxx:200
std::string okstr(bool b)
Convert boolean to "ok" or "not-ok".
Definition: StringTheory.h:98
bool parseXorList(CmdDef &cmddef, CmdFormDef &form, const TokenVec &tokens, size_t &pos, str::StringVec &literals)
Parse mutually exclusive list.
bool tokEq(const std::string strCmp, const TokenVec &tokens, size_t &pos)
Test if token at position is equal to string.
void setName(const std::string &strName)
Set argument&#39;s name.
Definition: CmdArgDef.cxx:190
int numOfArgs() const
Get the total number of arguments.
Definition: CmdFormDef.h:195
bool rnr::cmd::CommandLine::peekEq ( const std::string  strCmp,
const Token token 
) const
inlineprotected

Peek if token is equal to string.

The position cursor is not advance nor any error message logged.

Parameters
[in]strCmpString to compare token against.
[in]tokenLexical token.
Returns
Returns true on equal, false otherwise.

Definition at line 1789 of file CommandLine.h.

References rnr::cmd::Token::value().

Referenced by parseArg(), parseArgv0(), parseOptionalArgList(), parseRequiredArgList(), parseVariableArg(), parseVarMod(), and parseXorList().

1790  {
1791  return token.value() == strCmp;
1792  }
void CommandLine::popPrompt ( )

Pop prompt string from stack of prompts.

The new top prompt string will be used for user prompting.

Definition at line 1058 of file CommandLine.cxx.

References getPrompt(), m_prompts, m_readline, rnr::cmd::noprompt, and rnr::cmd::ReadLine::setPrompt().

Referenced by execCliTest().

1059 {
1060  if( !m_prompts.empty() )
1061  {
1062  m_prompts.pop_back();
1064  }
1065  else
1066  {
1068  }
1069 }
ReadLine m_readline
readline interface
Definition: CommandLine.h:1194
static const string noprompt
"no prompt" prompt value
PromptStack m_prompts
stack of prompt strings
Definition: CommandLine.h:1193
const std::string & getPrompt() const
Get the current prompt string.
void setPrompt(const std::string &strPrompt)
Set the prompt string.
Definition: ReadLine.h:413
int CommandLine::processInput ( const std::string &  strLine,
CmdExtArgVec argv 
)
protected

Process a line of input.

The line is tokenized and matched to the command with the best fit.

Parameters
[in]strLineLine of input.
[out]argvVector of extended arguments, with argv[0] being the command name argument.
Returns
On success, AOk(0) is returned. On error, a CommandLine error code (< 0) is returned. See getErroStr() and backtrace() to retrieve or print error(s).

Definition at line 1083 of file CommandLine.cxx.

References checkReadResult(), rnr::cmd::EBadSyntax, match(), and tokenizeInput().

Referenced by readCommand().

1084 {
1085  TokenVec tokens; // tokenized input arguments
1086  int argc; // argument count
1087  int rc; // return code
1088 
1089  argv.clear();
1090 
1091  //
1092  // The line is empty - find out why?
1093  //
1094  if( strLine.empty() )
1095  {
1096  rc = checkReadResult();
1097  }
1098 
1099  //
1100  // Tokenize the input line.
1101  //
1102  else if( (argc = (int)tokenizeInput(strLine, tokens)) < 0 )
1103  {
1104  // bad token - error string already set
1105  rc = EBadSyntax;
1106  }
1107 
1108  //
1109  // Line full of whitespace - again, find out why?
1110  //
1111  else if( argc == 0 )
1112  {
1113  rc = checkReadResult();
1114  }
1115 
1116  //
1117  // Otherwise match the input arguments to the best form of the best fit
1118  // command definition.
1119  //
1120  else
1121  {
1122  rc = match(tokens, argv);
1123  }
1124 
1125  return rc;
1126 }
int checkReadResult()
Check read input result.
virtual ssize_t tokenizeInput(const std::string &strInput, TokenVec &tokens)
Lexically analyze input string to generate a series of tokens.
int match(const TokenVec &tokens, CmdExtArgVec &argv)
Match the input tokens to the compiled commands to find the best fit.
std::vector< Token > TokenVec
vector of tokens type
Definition: Token.h:222
const int EBadSyntax
bad syntax
Definition: CmdCore.h:104
void CommandLine::pushPrompt ( const std::string &  strPrompt)

Push prompt string onto stack of prompts.

If in interactive mode, the user will be prompted with the prompt string found at the top of the prompt stack. If the stack or prompt string is empty, no prompt will be displayed. Any prompt is written to standard output (stdout).

Parameters
strPromptPrompt string.

Definition at line 1052 of file CommandLine.cxx.

References m_prompts, m_readline, and rnr::cmd::ReadLine::setPrompt().

Referenced by CommandLine(), and execTPush().

1053 {
1054  m_prompts.push_back(strPrompt);
1055  m_readline.setPrompt(strPrompt);
1056 }
ReadLine m_readline
readline interface
Definition: CommandLine.h:1194
PromptStack m_prompts
stack of prompt strings
Definition: CommandLine.h:1193
void setPrompt(const std::string &strPrompt)
Set the prompt string.
Definition: ReadLine.h:413
void CommandLine::pushToken ( const std::string &  strSource,
const size_t  start,
const ssize_t  cursor,
TokenVec tokens 
)
protected

Push token to the end of the generated tokens.

Parameters
strSourceSource string of tokens.
startStart token character position in source.
cursorCursor position in source.
[in,out]tokensVector of lexical tokens.

Definition at line 2383 of file CommandLine.cxx.

References getLineNum().

Referenced by lexQuotedString(), lexSyntaxParenExpr(), lexSyntaxWord(), lexWord(), logLexToken(), and tokenizeSyntax().

2387 {
2388  Token tok(strSource.substr(start, cursor-start),
2389  getLineNum(), start, cursor-1);
2390  tokens.push_back(tok);
2391 }
size_t getLineNum() const
Get the line number of the last read line.
Definition: CommandLine.h:853
Parsed token container class.
Definition: Token.h:84
virtual int rnr::cmd::CommandLine::readCommand ( int &  uid,
int &  iform,
str::StringVec argv 
)
inlinevirtual

Read an input line from stdin and match to the best compiled command.

Simple string argument version.

On success, no arguments indicate an empty input line. Otherwise, the command name argv[0] is guaranteed to be present in the vector.

Parameters
[out]uidMatched command unique id.
[out]iformMatched command form index.
[out]argvVector of arguments, with argv[0] being the command name.
Returns
On success, AOk(0) is returned. On error, a CommandLine error code (< 0) is returned. See getErroStr() and backtrace() to retrieve or print error(s).

Definition at line 683 of file CommandLine.h.

Referenced by readCommand(), and run().

684  {
685  return readCommand(stdin, uid, iform, argv);
686  }
virtual int readCommand(int &uid, int &iform, str::StringVec &argv)
Read an input line from stdin and match to the best compiled command.
Definition: CommandLine.h:683
virtual int rnr::cmd::CommandLine::readCommand ( CmdExtArgVec argv)
inlinevirtual

Read an input line from stdin and match to the best compiled command.

Extended argument version.

Each extended argument contains matched command context of:

  • the command's unique id and definition
  • form definition index
  • argument definition index
  • argument instance number for (future) argument repetition

On success, no arguments indicate an empty input line. Otherwise, the command name argv[0] is guaranteed to be present in the vector.

Extended arguments gives access to the compiled, matched command definition data such as number of required, optional, and total arguments, plus argument specific info such as name, type, etc.

Parameters
[out]uidMatched command unique id.
[out]argvVector of extended arguments, with argv[0] being the command name argument.
Returns
On success, AOk(0) is returned. On error, a CommandLine error code (< 0) is returned. See getErroStr() and backtrace() to retrieve or print error(s).

Definition at line 713 of file CommandLine.h.

References rnr::cmd::CmdExec::execute().

714  {
715  return readCommand(stdin, argv);
716  }
virtual int readCommand(int &uid, int &iform, str::StringVec &argv)
Read an input line from stdin and match to the best compiled command.
Definition: CommandLine.h:683
int CommandLine::readCommand ( FILE *  fp,
int &  uid,
int &  iform,
str::StringVec argv 
)
virtual

Read an input line from file fp and match to the best compiled command.

Simple string argument version.

On success, no arguments indicate an empty input line. Otherwise, the command name argv[0] is guaranteed to be present in the vector.

Parameters
fpInput file pointer.
[out]uidMatched command unique id.
[out]iformMatched command form index.
[out]argvVector of arguments, with argv[0] being the command name.
Returns
On success, AOk(0) is returned. On error, a CommandLine error code (< 0) is returned. See getErroStr() and backtrace() to retrieve or print error(s).

Definition at line 848 of file CommandLine.cxx.

References rnr::cmd::AOk, rnr::cmd::NoIndex, rnr::cmd::NoUid, readCommand(), and toVec().

849 {
850  CmdExtArgVec extargv;
851  int rc;
852 
853  argv.clear();
854 
855  uid = NoUid;
856  iform = NoIndex;
857 
858  if( ((rc = readCommand(fp, extargv)) == AOk) && (extargv.size() > 0) )
859  {
860  uid = extargv[0].uid();
861  iform = extargv[0].formIndex();
862 
863  toVec(extargv, argv);
864  }
865 
866  return rc;
867 }
void toVec(const CmdExtArgVec &v1, str::StringVec &v2)
Convert extended argument vector to string argument vector.
const int NoUid
Special values.
Definition: CmdCore.h:116
std::vector< CmdExtArg > CmdExtArgVec
vector of ext args type
Definition: CmdExtArg.h:397
const int NoIndex
no index
Definition: CmdCore.h:117
const int AOk
(0) A-Ok, no error, success, good
Definition: CmdCore.h:93
virtual int readCommand(int &uid, int &iform, str::StringVec &argv)
Read an input line from stdin and match to the best compiled command.
Definition: CommandLine.h:683
int CommandLine::readCommand ( FILE *  fp,
CmdExtArgVec argv 
)
virtual

Read an input line from file fp and match to the best compiled command.

Extended argument version.

Each extended argument contains matched command context of:

  • the command's unique id and definition
  • form definition index
  • argument definition index
  • argument instance number for (future) argument repetition

On success, no arguments indicate an empty input line. Otherwise, the command name argv[0] is guaranteed to be present in the vector.

Extended arguments gives access to the compiled, matched command definition data such as number of required, optional, and total arguments, plus argument specific info such as name, type, etc.

Parameters
fpInput file pointer.
[out]argvVector of extended arguments, with argv[0] being the command name argument.
Returns
On success, AOk(0) is returned. On error, a CommandLine error code (< 0) is returned. See getErroStr() and backtrace() to retrieve or print error(s).

Definition at line 869 of file CommandLine.cxx.

References rnr::cmd::AOk, backtrace(), rnr::bookmark(), rnr::LogBook::clear(), rnr::cmd::ENoExec, rnr::eoe(), getBtEnable(), getErrorStr(), getLineNum(), getName(), rnr::cmd::ReadLine::ireadLine(), LOGDIAG3_STREAM, LOGERROR_STREAM, m_cmdDefs, m_log, m_readline, numOfCmds(), processInput(), and rnr::cmd::ReadLine::rlreadLine().

870 {
871  string strLine;
872  int rc;
873 
874  m_log.clear();
875  m_log << bookmark(markExec) << labelExec << __func__ << eoe;
876 
877  argv.clear();
878 
879  //
880  // Preliminary checks.
881  //
882  if( numOfCmds() == 0 )
883  {
884  m_log << labelNoExec << "No commands added to interface." << eoe;
886  return ENoExec;
887  }
888  else if( !isDefined() )
889  {
890  m_log << labelNoExec << "Commands not fully compiled." << eoe;
892  return ENoExec;
893  }
894 
895  //
896  // Read a line of input.
897  //
898  if( fileno(fp) == fileno(stdin) )
899  {
900  strLine = m_readline.rlreadLine();
901  }
902  else
903  {
904  strLine = m_readline.ireadLine(fp);
905  }
906 
907  m_log << labelInput << "stdin" << "[" << getLineNum() << "] "
908  << strLine << eoe;
909 
910  //
911  // Process input, match to best command.
912  //
913  if( (rc = processInput(strLine, argv)) == AOk )
914  {
915  m_log << labelExec << "Ok" << eoe;
916 
917  if( argv.size() > 0 )
918  {
919  LOGDIAG3_STREAM("Command "
920  << m_cmdDefs[argv[0].uid()].getName()
921  << "(" << argv[0].uid() << "), form "
922  << argv[0].formIndex() << " matched.");
923  }
924  }
925  else
926  {
927  m_log << labelFail << "Input not matched to any command." << eoe;
928 
929  LOGDIAG3("No command matched to input.");
930  }
931 
932  if( getBtEnable() )
933  {
934  backtrace(cerr);
935  }
936 
937  return rc;
938 }
std::string & rlreadLine()
Interactively read a line of input from standard input (stdin).
Definition: ReadLine.cxx:174
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
ReadLine m_readline
readline interface
Definition: CommandLine.h:1194
size_t getLineNum() const
Get the line number of the last read line.
Definition: CommandLine.h:853
bool getBtEnable() const
Test if backtracing is enabled.
Definition: CommandLine.h:499
void clear()
Clear the log book and bookmarks, along with any pending entry.
Definition: LogBook.cxx:521
int numOfCmds() const
Get the total number of added commands.
Definition: CommandLine.h:1108
std::ostream & backtrace(std::ostream &os, const bool bAll=false) const
Insert trace and error log backtrace into output stream.
LogBook & eoe(LogBook &log)
LogBook end-of-entry stream manipulator.
Definition: LogBook.cxx:926
const int ENoExec
cannot execute
Definition: CmdCore.h:105
#define LOGDIAG3_STREAM(args)
Diagnostic level 3 stream logging.
Definition: LogStream.h:115
const int AOk
(0) A-Ok, no error, success, good
Definition: CmdCore.h:93
#define LOGERROR_STREAM(args)
Error stream logging.
Definition: LogStream.h:167
LogBook & bookmark(LogBook &log)
LogBook bookmark stream manipulator.
Definition: LogBook.cxx:932
const std::string & getName() const
Get command line interface&#39;s name.
Definition: CommandLine.h:1040
std::string & ireadLine()
Interactively read a line of input from standard input (stdin).
Definition: ReadLine.h:313
const std::string & getErrorStr() const
Get the most recent error.
int processInput(const std::string &strLine, CmdExtArgVec &argv)
Process a line of input.
CmdDefMap m_cmdDefs
map of added command definitions
Definition: CommandLine.h:1191
int CommandLine::removeAllCommands ( )
virtual

Remove all commands from command line interface.

Returns
On success, AOk(0) is returned. On error, a CommandLine error code (< 0) is returned. See getErroStr() and backtrace() to retrieve or print error(s).

Definition at line 619 of file CommandLine.cxx.

References rnr::cmd::AOk, rnr::eoe(), m_bIsCompiled, m_cmdDefs, and m_log.

620 {
621  m_cmdDefs.clear();
622  m_bIsCompiled = false;
623  m_log << "All commands removed." << eoe;
624  return AOk;
625 }
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
bool m_bIsCompiled
has [not] been successfully compiled
Definition: CommandLine.h:1190
LogBook & eoe(LogBook &log)
LogBook end-of-entry stream manipulator.
Definition: LogBook.cxx:926
const int AOk
(0) A-Ok, no error, success, good
Definition: CmdCore.h:93
CmdDefMap m_cmdDefs
map of added command definitions
Definition: CommandLine.h:1191
int CommandLine::removeCommand ( const int  uid)
virtual

Remove command from command line interface.

No re-comiple is necessary.

Parameters
uidCommand unique id.
Returns
On success, AOk(0) is returned. On error, a CommandLine error code (< 0) is returned. See getErroStr() and backtrace() to retrieve or print error(s).

Definition at line 569 of file CommandLine.cxx.

References rnr::cmd::AOk, cmdAt(), rnr::cmd::EBadVal, rnr::eoe(), getErrorStr(), rnr::cmd::CmdDef::getUid(), LOGERROR_STREAM, m_bIsCompiled, m_cmdDefs, m_cmdExecs, m_log, and rnr::cmd::NoUid.

Referenced by execTRemove().

570 {
571  CmdDefIter dpos; // definition position
572  CmdExecIter epos; // execution position
573  int rc; // return code
574 
575  if( uid == NoUid )
576  {
577  rc = EBadVal;
578  }
579  else if( (dpos = m_cmdDefs.find(uid)) == m_cmdDefs.end() )
580  {
581  rc = EBadVal;
582  }
583  else
584  {
585  // remove command definition
586  m_cmdDefs.erase(dpos);
587 
588  // remove any command execution function
589  if( (epos = m_cmdExecs.find(uid)) != m_cmdExecs.end() )
590  {
591  m_cmdExecs.erase(epos);
592  }
593 
594  if( m_cmdDefs.size() == 0 )
595  {
596  m_bIsCompiled = false;
597  }
598 
599  m_log << "Command " << uid << " removed." << eoe;
600  rc = AOk;
601  }
602 
603  if( rc != AOk )
604  {
605  m_log << "No command with uid " << uid << " found." << eoe;
607  }
608 
609  return rc;
610 }
CmdExecMap::iterator CmdExecIter
exec iterator type
Definition: CommandLine.h:424
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
bool m_bIsCompiled
has [not] been successfully compiled
Definition: CommandLine.h:1190
const int NoUid
Special values.
Definition: CmdCore.h:116
CmdExecMap m_cmdExecs
map of added command executions
Definition: CommandLine.h:1192
CmdDefMap::iterator CmdDefIter
cmd iterator type
Definition: CommandLine.h:417
LogBook & eoe(LogBook &log)
LogBook end-of-entry stream manipulator.
Definition: LogBook.cxx:926
const int AOk
(0) A-Ok, no error, success, good
Definition: CmdCore.h:93
const int EBadVal
bad value
Definition: CmdCore.h:108
#define LOGERROR_STREAM(args)
Error stream logging.
Definition: LogStream.h:167
const std::string & getErrorStr() const
Get the most recent error.
CmdDefMap m_cmdDefs
map of added command definitions
Definition: CommandLine.h:1191
virtual int rnr::cmd::CommandLine::removeCommand ( const std::string &  strName)
virtual

Remove command from command line interface.

No re-comiple is necessary.

Parameters
strNameCommand name.
Returns
On success, AOk(0) is returned. On error, a CommandLine error code (< 0) is returned. See getErroStr() and backtrace() to retrieve or print error(s).
int CommandLine::removeDataSection ( const std::string &  ns)

Remove a data section from the command-line interface.

If a deallocation function was specified, the section data is also deleted. Otherwise, the data remains intact.

Parameters
nsNamespace of data section to remove.
Returns
On success, AOk(0) is returned. On error, a CommandLine error code (< 0) is returned. See getErroStr() and backtrace() to retrieve or print error(s).

Definition at line 809 of file CommandLine.cxx.

References rnr::cmd::AOk, rnr::cmd::EBadVal, rnr::cmd::ENoExec, isReservedDataSection(), LOGERROR_STREAM, and m_dataSects.

810 {
811  DataSectIter pos = m_dataSects.find(ns);
812 
813  if( pos != m_dataSects.end() )
814  {
815  LOGERROR_STREAM("No data section '" << ns << "' exist - cannot remove.");
816  return EBadVal;
817  }
818  else if( isReservedDataSection(pos->first) )
819  {
820  LOGERROR_STREAM("Reserved data section '" << ns << "' cannot be removed.");
821  return ENoExec;
822  }
823  else
824  {
825  m_dataSects.erase(pos);
826  return AOk;
827  }
828 }
const int ENoExec
cannot execute
Definition: CmdCore.h:105
const int AOk
(0) A-Ok, no error, success, good
Definition: CmdCore.h:93
const int EBadVal
bad value
Definition: CmdCore.h:108
#define LOGERROR_STREAM(args)
Error stream logging.
Definition: LogStream.h:167
DataSectMap::iterator DataSectIter
iterator type
Definition: CommandLine.h:431
DataSectMap m_dataSects
data sections
Definition: CommandLine.h:1196
bool isReservedDataSection(const std::string &ns) const
Test if the namespace is a command-line interface reserved name.
void CommandLine::rlArgDefs ( const std::string &  strSubtext,
std::vector< CmdArgDef * > &  argdefs 
)
protected

Build list of all command argument definitions that match completed subtext.

Parameters
[in]strSubtextComplete subtext string.
[out]argdefsList of matched argument definitions.

Definition at line 1654 of file CommandLine.cxx.

References rnr::cmd::CmdFormDef::argAt(), rnr::cmd::CmdArgDef::getParentCmdUid(), rnr::cmd::CmdArgDef::getParentFormIndex(), m_bIgnoreCase, m_cmdDefs, rnr::cmd::CmdArgDef::match(), rnr::cmd::CmdFormDef::numOfArgs(), and tokenizeInput().

Referenced by rlGenerator().

1656 {
1657  CmdDefIter iter; // command definition iterator
1658  vector<CmdArgDef*> v[2]; // work swap vectors of argument definitions
1659  int tog0, tog1; // vector toggle source/destination indices
1660  StringVec tokens; // input tokens
1661  size_t argc; // token working argument count
1662  size_t i, j; // working indices
1663 
1664  argdefs.clear();
1665 
1666  tokenizeInput(strSubtext, tokens);
1667 
1668  tog0 = 0, tog1 = 1;
1669 
1670  //
1671  // Seed with argv0 (command).
1672  //
1673  for(iter = m_cmdDefs.begin(); iter != m_cmdDefs.end(); ++iter)
1674  {
1675  for(j = 0; j < iter->second.numOfForms(); ++j)
1676  {
1677  CmdFormDef &form = iter->second.formAt(j);
1678  v[tog0].push_back(&form.argAt(0));
1679  }
1680  }
1681 
1682  //
1683  // Walk across token arguments, paring unmatched argument defs from list.
1684  //
1685  for(argc = 0; argc < tokens.size(); ++argc)
1686  {
1687  v[tog1].clear();
1688 
1689  for(i = 0; i < v[tog0].size(); ++i)
1690  {
1691  CmdArgDef *p = v[tog0][i];
1692 
1693  if( p->match(tokens[argc], m_bIgnoreCase) > 0.0 )
1694  {
1695  CmdFormDef &form =
1696  m_cmdDefs[p->getParentCmdUid()].formAt(p->getParentFormIndex());
1697 
1698  if( argc+1 < form.numOfArgs() )
1699  {
1700  v[tog1].push_back(&form.argAt(argc+1));
1701  }
1702  }
1703  }
1704 
1705  tog0 = tog1;
1706  tog1 = (tog1 + 1) % 2;
1707  }
1708 
1709  // copy to interface parameter
1710  for(i = 0; i < v[tog0].size(); ++i)
1711  {
1712  argdefs.push_back(v[tog0][i]);
1713  }
1714 }
std::vector< std::string > StringVec
Useful types.
Definition: StringTheory.h:83
virtual ssize_t tokenizeInput(const std::string &strInput, TokenVec &tokens)
Lexically analyze input string to generate a series of tokens.
CmdArgDef & argAt(const int nIndex)
Get form&#39;s modifiable argument at index.
Definition: CmdFormDef.cxx:188
double match(const std::string &strArg, const bool bIgnoreCase=false) const
Match argument string against argument definition pattern.
Definition: CmdArgDef.cxx:326
Command argument compiled definition class.
Definition: CmdArgDef.h:89
int getParentFormIndex() const
Get parent command form&#39;s index.
Definition: CmdArgDef.h:184
CmdDefMap::iterator CmdDefIter
cmd iterator type
Definition: CommandLine.h:417
int getParentCmdUid() const
Get parent command&#39;s unique id.
Definition: CmdArgDef.h:174
bool m_bIgnoreCase
do [not] ignore case on commands
Definition: CommandLine.h:1188
Compiled command form defintion class.
Definition: CmdFormDef.h:91
CmdDefMap m_cmdDefs
map of added command definitions
Definition: CommandLine.h:1191
int numOfArgs() const
Get the total number of arguments.
Definition: CmdFormDef.h:195
int CommandLine::rlBuildReadLineGenerator ( )
protectedvirtual

Perform any necessary pre-processing to prepare for command line TAB completion.

Note
Nothing is needed for the CommandLine base class.
Returns
On success, AOk(0) is returned. On error, a CommandLine error code (< 0) is returned. See getErroStr() and backtrace() to retrieve or print error(s).

Definition at line 1592 of file CommandLine.cxx.

References rnr::cmd::AOk.

Referenced by compile().

1593 {
1594  return AOk;
1595 }
const int AOk
(0) A-Ok, no error, success, good
Definition: CmdCore.h:93
const string CommandLine::rlGenerator ( const std::string &  strText,
int  nIndex,
const std::string &  strContext,
int  nStart,
int  nEnd,
unsigned &  uFlags 
)
protectedvirtual

TAB completion generator.

See ReadLine::AltAppGenFunc for description of a ReadLine generator.

Parameters
strTextPartial text string to complete.
nIndexMatch candidate index starting from 0.
strContextGenerator context (i.e. input buffer).
nStartStarting index in context of text.
nEndEnding index in context of the position immediately after the end of text. If nStart equals nEnd, then empty text.
[out]uFlagsTAB completion modifier flags.
Returns
Match or empty string.

Definition at line 1616 of file CommandLine.cxx.

References rlArgDefs(), rnr::cmd::RlTabEnd, and rlTabList().

1622 {
1623  static vector<CmdArgDef*> argdefs;
1624 
1625  StringVec tabList;
1626  size_t i;
1627 
1628  //cerr << "{text=" << strText
1629  // << ", index=" << nIndex
1630  // << ", context=" << strContext
1631  // << ", start=" << nStart
1632  // << ", end=" << nEnd
1633  // << "}" << endl;
1634 
1635  if( nIndex == 0 )
1636  {
1637  //cerr << "rebuild args" << endl;
1638  argdefs.clear();
1639  rlArgDefs(strContext.substr(0, nStart), argdefs);
1640  }
1641 
1642  rlTabList(strText, argdefs, tabList, uFlags);
1643 
1644  if( nIndex < tabList.size() )
1645  {
1646  return tabList[nIndex];
1647  }
1648  else
1649  {
1650  return RlTabEnd;
1651  }
1652 }
std::vector< std::string > StringVec
Useful types.
Definition: StringTheory.h:83
void rlArgDefs(const std::string &strSubtext, std::vector< CmdArgDef * > &argdefs)
Build list of all command argument definitions that match completed subtext.
static const char * RlTabEnd
no more matches value (empty string)
Definition: ReadLine.h:94
void rlTabList(const std::string &strText, std::vector< CmdArgDef * > &argdefs, str::StringVec &tabList, unsigned &uFlags)
Build TAB completion list and set appropriate readline modifiers.
const string CommandLine::rlGeneratorWrapper ( void *  pAppArg,
const std::string &  strText,
int  nIndex,
const std::string &  strContext,
int  nStart,
int  nEnd,
unsigned &  uFlags 
)
staticprotected

Static TAB completion generator wrapper.

See ReadLine::AltAppGenFunc for description of a ReadLine generator.

Parameters
pAppArgPointer to this CommandLine object.
strTextPartial text string to complete.
nIndexMatch candidate index starting from 0.
strContextGenerator context (i.e. input buffer).
nStartStarting index in context of text.
nEndEnding index in context of the position immediately after the end of text. If nStart equals nEnd, then empty text.
[out]uFlagsTAB completion modifier flags.
Returns
Match or empty string.

Definition at line 1597 of file CommandLine.cxx.

References rnr::cmd::emptystring.

Referenced by compile().

1604 {
1605  if( pAppArg != NULL )
1606  {
1607  return ((CommandLine *)pAppArg)->rlGenerator(strText, nIndex, strContext,
1608  nStart, nEnd, uFlags);
1609  }
1610  else
1611  {
1612  return emptystring;
1613  }
1614 }
CommandLine class.
Definition: CommandLine.h:444
const std::string emptystring
"" empty string
Definition: CmdCore.cxx:82
bool CommandLine::rlPartialMatch ( const std::string &  strText,
const std::string  strLiteral,
const size_t  uLen 
)
protected

Match partial text agains literal string.

Ignore case is taken into account when strings are compared.

Parameters
[in]strTextPartial text string to complete.
[in]strLiteralLiteral text string to compare.
[in]uLenNumber of characters to match.
Returns
Returns true on partial match, false otherwise.

Definition at line 1860 of file CommandLine.cxx.

References rnr::str::lowercase(), and m_bIgnoreCase.

Referenced by rlTabList().

1863 {
1864  if( m_bIgnoreCase )
1865  {
1866  return lowercase(strText) == lowercase(strLiteral.substr(0, uLen));
1867  }
1868  else
1869  {
1870  return strText == strLiteral.substr(0, uLen);
1871  }
1872 }
std::string lowercase(const std::string &str)
Convert in-place string to lower case.
bool m_bIgnoreCase
do [not] ignore case on commands
Definition: CommandLine.h:1188
void CommandLine::rlTabList ( const std::string &  strText,
std::vector< CmdArgDef * > &  argdefs,
str::StringVec tabList,
unsigned &  uFlags 
)
protected

Build TAB completion list and set appropriate readline modifiers.

Parameters
[in]strTextPartial text string to complete.
[in]argdefsList of matched argument definitions.
[out]tabListList of TAB completion matches.
[out]uFlagsTAB completion modifier flags.

Definition at line 1716 of file CommandLine.cxx.

References rnr::cmd::CmdArgDef::ArgTypeBoolean, rnr::cmd::CmdArgDef::ArgTypeFile, rnr::cmd::CmdArgDef::ArgTypeFpn, rnr::cmd::CmdArgDef::ArgTypeIdentifier, rnr::cmd::CmdArgDef::ArgTypeInteger, rnr::cmd::CmdArgDef::ArgTypeLiteral, rnr::cmd::CmdArgDef::ArgTypeMultiWord, rnr::cmd::CmdArgDef::ArgTypeRegEx, rnr::cmd::CmdArgDef::ArgTypeUndef, rnr::cmd::CmdArgDef::ArgTypeWord, rnr::str::FalseHood, rnr::cmd::ReadLine::FlagTabNoDefault, rnr::cmd::ReadLine::FlagTabNoFilename, rnr::cmd::ReadLine::FlagTabNoSpace, rnr::str::gcss(), rlPartialMatch(), and rnr::str::TruthHood.

Referenced by rlGenerator().

1720 {
1721  size_t len; // length of input text
1722  set<string> A; // set with unique keys == values
1723  set<string>::iterator iter, jter; // bidirectional set iterators
1724  string str; // working string
1725  size_t i, j, min; // working indices, minimum
1726 
1727  // clear TAB list of all existing candidates
1728  tabList.clear();
1729 
1730  // no filename completion
1731  uFlags = ReadLine::FlagTabNoFilename;
1732 
1733  // nothing to TAB complete
1734  if( argdefs.size() == 0 )
1735  {
1736  return;
1737  }
1738 
1739  // length of partial text to complete
1740  len = strText.size();
1741 
1742  //
1743  // Build tab completion super list.
1744  //
1745  // Note: Sets automatically handle duplicates.
1746  //
1747  for(i = 0; i < argdefs.size(); ++i)
1748  {
1749  switch( argdefs[i]->getType() )
1750  {
1751  // Find all literals that partially match text.
1753  for(j = 0; j < argdefs[i]->numOfLiterals(); ++j)
1754  {
1755  str = argdefs[i]->literalAt(j);
1756 
1757  if( rlPartialMatch(strText, str, len) )
1758  {
1759  A.insert(str);
1760  }
1761  }
1762  break;
1763 
1765  for(j = 0; FalseHood[j] != NULL; ++j)
1766  {
1767  if( rlPartialMatch(strText, FalseHood[j], len) )
1768  {
1769  // bit of hack. don't want 'false' and 'f' in TAB complition list
1770  if( FalseHood[j] != "f" )
1771  {
1772  A.insert(FalseHood[j]);
1773  }
1774  }
1775  }
1776  for(j = 0; TruthHood[j] != NULL; ++j)
1777  {
1778  if( rlPartialMatch(strText, TruthHood[j], len) )
1779  {
1780  // bit of hack. don't want 'true' and 't' in TAB complition list
1781  if( TruthHood[j] != "t" )
1782  {
1783  A.insert(TruthHood[j]);
1784  }
1785  }
1786  }
1787  break;
1788 
1789  // Argument types not posible to TAB complete, provide syntax if no text.
1794  case CmdArgDef::ArgTypeFpn:
1796  if( len == 0 )
1797  {
1798  A.insert(argdefs[i]->constructSyntax());
1799  uFlags |= ReadLine::FlagTabNoDefault;
1800  }
1801  break;
1802 
1803  // Filename argument type, allow filename completion.
1805  uFlags &= ~ReadLine::FlagTabNoFilename;
1806  break;
1807 
1808  // Unknown.
1810  default:
1811  break;
1812  }
1813  }
1814 
1815  //
1816  // Find the greatest common prefix substring.
1817  //
1818  if( !(uFlags & ReadLine::FlagTabNoDefault) && (A.size() > 1) )
1819  {
1820  jter = A.begin();
1821  iter = jter++;
1822 
1823  size_t min = iter->size();
1824 
1825  for(; (jter != A.end()) && (min > 0); ++iter, ++jter)
1826  {
1827  j = gcss(*iter, *jter);
1828 
1829  if( j < min )
1830  {
1831  min = j;
1832  }
1833  }
1834 
1835  // Common substring is longer than text. This is the only default TAB entry.
1836  if( min > len )
1837  {
1838  str = *A.begin();
1839  A.clear();
1840  A.insert(str.substr(0, min));
1841  uFlags |= ReadLine::FlagTabNoSpace;
1842  }
1843  }
1844 
1845  //
1846  // Copy set to vector list
1847  //
1848  for(iter = A.begin(); iter != A.end(); ++iter)
1849  {
1850  tabList.push_back(*iter);
1851  }
1852 
1853  // Disable default if multiple unique matches.
1854  if( tabList.size() > 1 )
1855  {
1856  uFlags |= ReadLine::FlagTabNoDefault;
1857  }
1858 }
no filename TAB completion attempt
Definition: ReadLine.h:124
floating point number (double)
Definition: CmdArgDef.h:104
undefined argument type
Definition: CmdArgDef.h:97
const char * TruthHood[]
strings that equate to true
no space(&#39; &#39;) after TAB completion
Definition: ReadLine.h:125
identifier (C conforming)
Definition: CmdArgDef.h:101
bool rlPartialMatch(const std::string &strText, const std::string strLiteral, const size_t uLen)
Match partial text agains literal string.
ReadLine class provides a C++ wrapper around the readline C library.
Definition: ReadLine.h:112
no default TAB completion match
Definition: ReadLine.h:123
any (quoted) character sequence
Definition: CmdArgDef.h:100
size_t gcss(const std::string &str1, const std::string &str2, const size_t pos=0)
Find the length of the Greatest Common SubString.
const char * FalseHood[]
Falsehood and truthhood strings. Each list termintate with a NULL.
any non-whitespace contiguous char sequence
Definition: CmdArgDef.h:99
void rnr::cmd::CommandLine::setBtEnable ( bool  bEnable)
inline

Enable/disable backtracing.

Parameters
bEnableEnable(true) or Disable(false).

Definition at line 510 of file CommandLine.h.

References rnr::cmd::DataSectNsCore.

Referenced by rnr::cmd::addons::execBtEnable().

511  {
512  ((DataSectCore*)m_dataSects.at(DataSectNsCore).data())->m_bBacktrace =
513  bEnable;
514  }
const char *const DataSectNsCore
Reserved command line data section namespaces.
Definition: CmdCore.h:141
DataSectMap m_dataSects
data sections
Definition: CommandLine.h:1196
void rnr::cmd::CommandLine::setLineNum ( const size_t  uLineNum)
inline

Set the current line number.

Parameters
Linenumber.

Definition at line 863 of file CommandLine.h.

864  {
865  m_readline.setLineNum(uLineNum);
866  }
void setLineNum(const size_t uLineNum)
Set the current line number.
Definition: ReadLine.h:453
ReadLine m_readline
readline interface
Definition: CommandLine.h:1194
virtual ssize_t rnr::cmd::CommandLine::tokenizeInput ( const std::string &  strInput,
TokenVec tokens 
)
virtual

Lexically analyze input string to generate a series of tokens.

Tokens are separated by whitespace.

Each tokens is either:

  • A contiguous sequence of non-whitespace characters.
  • An escapable sequence of characters delineated by double quotes '"'.
<token-list> ::= <token>
| <token-list> <token>
<token> ::= <word>
| <quoted-string>
<word> ::= {NONWHITE_CHAR}+
<qouted-string> ::= '"' {ESCAPABLE_CHAR}* '"'
Parameters
[in]strInputInput string to analyze.
[out]tokensGenerated tokens.
Returns
On success, returns size (count). On error, a CommandLine error code (< 0) is returned. See getErroStr() and backtrace() to retrieve or print error(s).

Referenced by backtrace(), processInput(), and rlArgDefs().

virtual ssize_t rnr::cmd::CommandLine::tokenizeInput ( const std::string &  strInput,
str::StringVec tokens 
)
virtual

Lexically analyze input string to generate a series of string tokens.

See tokenize()

Parameters
[in]strInputInput string to analyze.
[out]tokensGenerated string tokens.
Returns
On success, returns size (count). On error, a CommandLine error code (< 0) is returned. See getErroStr() and backtrace() to retrieve or print error(s).
ssize_t CommandLine::tokenizeSyntax ( const std::string &  strSyntax,
TokenVec tokens 
)
protectedvirtual

Lexically analyze extened usage syntax string to generate a series of tokens.

Tokens are separated by either whitespace, parenthetical blocks, or syntax special characters.

Parameters
[in]strSyntaxSyntax string to analyze.
[out]tokensGenerated tokens.
Returns
On success, returns size (count). On error, a CommandLine error code (< 0) is returned. See getErroStr() and backtrace() to retrieve or print error(s).

Definition at line 2042 of file CommandLine.cxx.

References rnr::cmd::isoparen(), rnr::cmd::isspecial(), lexSyntaxParenExpr(), lexSyntaxWord(), and pushToken().

Referenced by compile().

2043 {
2044  size_t len; // length of syntax string
2045  ssize_t cursor; // cursor character position along syntax string
2046  size_t start; // start character position of token in syntax string
2047 
2048  CL_DBG_CALL_IN("\"" << strSyntax << "\", tokens", endl);
2049 
2050  tokens.clear();
2051 
2052  len = strSyntax.length();
2053 
2054  for(cursor = 0; (cursor >= 0) && (cursor < len); )
2055  {
2056  // find start of the next token
2057  while( (cursor < len) && isspace((int)strSyntax[cursor]) )
2058  {
2059  ++cursor;
2060  }
2061 
2062  // no more tokens
2063  if( cursor >= len )
2064  {
2065  break;
2066  }
2067 
2068  // new parenthetical expression
2069  if( isoparen(strSyntax[cursor]) )
2070  {
2071  cursor = lexSyntaxParenExpr(strSyntax, cursor, tokens);
2072  }
2073 
2074  // special character token
2075  else if( isspecial(strSyntax[cursor]) )
2076  {
2077  start = cursor++;
2078  pushToken(strSyntax, start, cursor, tokens);
2079  }
2080 
2081  // new contiguous word token
2082  else
2083  {
2084  cursor = lexSyntaxWord(strSyntax, cursor, tokens);
2085  }
2086  }
2087 
2088 #ifdef CL_ENABLE_DEBUG
2089  {
2090  stringstream ss;
2091  string sep;
2092  for(size_t i = 0; i < tokens.size(); ++i)
2093  {
2094  ss << sep << tokens[i];
2095  sep = ", ";
2096  }
2097  CL_DBG_CALL_OUT_NL(ss.str());
2098  }
2099 #endif // CL_ENABLE_DEBUG
2100 
2101  return cursor >= 0? (ssize_t)tokens.size(): cursor;
2102 }
static bool isoparen(int c)
Test if c is a open parenthesis character.
virtual ssize_t lexSyntaxParenExpr(const std::string &strSyntax, ssize_t cursor, TokenVec &tokens)
Syntax parenthetical expression lexical analyzer.
virtual ssize_t lexSyntaxWord(const std::string &strSyntax, ssize_t cursor, TokenVec &tokens)
Syntax word lexical analyzer.
static bool isspecial(int c)
Command usage syntax special characters.
void pushToken(const std::string &strSource, const size_t start, const ssize_t cursor, TokenVec &tokens)
Push token to the end of the generated tokens.
bool CommandLine::tokEq ( const std::string  strCmp,
const TokenVec tokens,
size_t &  pos 
)
protected

Test if token at position is equal to string.

If equal, the position cursor is advanced on position. If not equal, an error message will be logged.

Parameters
[in]strCmpString to compare token against.
[in]tokensLexical tokens generated from the syntax usage.
[in,out]posThe position in the token vector. Advanced 1 position if equal.
Returns
Returns true on equal, false otherwise.

Definition at line 3109 of file CommandLine.cxx.

References rnr::eoe(), getErrorStr(), LOGERROR_STREAM, m_log, and rnr::str::okstr().

Referenced by parseOptionalArgList(), parseVariableArg(), parseVarMod(), parseXorList(), and parseXorListArg().

3112 {
3113  bool bOk;
3114 
3115  CL_DBG_CALL_IN("input, strcmp=\"" << strCmp << "\", "
3116  << "tokens, pos=" << pos, " ");
3117 
3118  if( pos >= tokens.size() )
3119  {
3120  m_log << labelSyntax << "Token " << pos << " '" << strCmp
3121  << "' does not exist." << eoe;
3123  bOk = false;
3124  }
3125 
3126  else if( tokens[pos].value() != strCmp )
3127  {
3128  m_log << labelSyntax << "Expected token '" << strCmp << "'"
3129  << ", but found " << tokens[pos]
3130  << eoe;
3132  bOk = false;
3133  }
3134 
3135  else
3136  {
3137  ++pos;
3138  bOk = true;
3139  }
3140 
3141  CL_DBG_CALL_OUT_IL(okstr(bOk) << ", pos=" << pos);
3142 
3143  return bOk;
3144 }
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
LogBook & eoe(LogBook &log)
LogBook end-of-entry stream manipulator.
Definition: LogBook.cxx:926
#define LOGERROR_STREAM(args)
Error stream logging.
Definition: LogStream.h:167
std::string okstr(bool b)
Convert boolean to "ok" or "not-ok".
Definition: StringTheory.h:98
const std::string & getErrorStr() const
Get the most recent error.
bool CommandLine::tokIdentifier ( const TokenVec tokens,
size_t &  pos 
)
protected

Test if string has valid identifier syntax.

Parameters
[in]tokensLexical tokens generated from the syntax usage.
[in,out]posThe position in the token vector. Advanced 1 position if valid identifier.
Returns
Returns true or false.

Definition at line 3146 of file CommandLine.cxx.

References rnr::eoe(), getErrorStr(), rnr::cmd::isIdentifier(), LOGERROR_STREAM, m_log, and rnr::str::okstr().

Referenced by parseIdentifier().

3147 {
3148  bool bOk;
3149 
3150  CL_DBG_CALL_IN("tokens=" << tokens.size() << ", pos=" << pos, " ");
3151 
3152  bOk = isIdentifier(tokens[pos].value());
3153 
3154  if( bOk )
3155  {
3156  ++pos;
3157  }
3158  else
3159  {
3160  m_log << labelSyntax << "Invalid identifier " << tokens[pos] << eoe;
3162  }
3163 
3164  CL_DBG_CALL_OUT_IL(okstr(bOk) << ", pos=" << pos);
3165 
3166  return bOk;
3167 }
LogBook m_log
trace and error log
Definition: CommandLine.h:1195
LogBook & eoe(LogBook &log)
LogBook end-of-entry stream manipulator.
Definition: LogBook.cxx:926
#define LOGERROR_STREAM(args)
Error stream logging.
Definition: LogStream.h:167
std::string okstr(bool b)
Convert boolean to "ok" or "not-ok".
Definition: StringTheory.h:98
bool isIdentifier(const std::string &str)
Test if string is a valid identifier.
const std::string & getErrorStr() const
Get the most recent error.
void CommandLine::toVec ( const CmdExtArgVec v1,
str::StringVec v2 
)
protected

Convert extended argument vector to string argument vector.

Parameters
[in]v1Extended argument vector.
[out]v2String argument vector.

Definition at line 1529 of file CommandLine.cxx.

Referenced by addToHistory(), and readCommand().

1530 {
1531  for(size_t i = 0; i < v1.size(); ++i)
1532  {
1533  v2.push_back(v1[i].arg());
1534  }
1535 }

Friends And Related Function Documentation

std::ostream& operator<< ( std::ostream &  os,
const CommandLine cl 
)
friend

Insert object into output stream.

Parameters
osOutput stream.
clObject to insert.
Returns
Reference to output stream.

The documentation for this class was generated from the following files: