Search code examples
c++pythoninterpreterinteractive-shell

Developing an interactive shell


I have an application; to interact with it I have to develop an interactive shell. The shell will take input from user and dispatch it to the server, which will process and return a response.

In the past I have done such things, but they typically had the following format:

Shell>> COMMAND arg1 arg2 arg3 ..

and my implementation was in a manner similiar to:

/* Mock implementation */
while(true) {
   in = readline()
   tokens = in.split(' ') //split based on space
   switch(token[0])  {
      case "Command_a": processA(token[1], token[2])
      case "Command_b": processB(token[1], token[2], token[3])
   }
}

This time I have to work with more extensive grammar for user input. If I use my current approach, it will make things very difficult with lots of if , if-elseif-else, if-else, switch statements for both parsing and generating response.

How can I approach this problem in a manner that will make the interpreter modular and maintainable? What are some ways in which popular CLI-Interface are implemented? I will really appreciate some code examples.

PS: Language choices limited C++/Python


Solution

  • You can develop your own parser and interpreter using bison and flex, but probably wiser is to embed an existing interpreter like Python, Lua or Squirrel.