Home > Articles > Programming > C/C++

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Coding the Driver

In addition to coding the individual states as classes, you also need to create a driver for the class. Like the states, the driver is derived from a class in the framework. Here’s a sample driver; first, the class definition:

class Calculator : public FSMDriver {
public:
  queue<CalcStackItem *> PostFixQueue;
  stack<char> OperatorStack;
  FSMState<Calculator> *start;
  Calculator();
  void Run(char *chars, FSMState<Calculator> *StartState);
  double Perform();
};

This class includes special members for the particular state machine I’m building, a calculator. It also includes an overloaded Run method that actually runs the state machine (although all it really does is call the Run method in the base class and catch exceptions for invalid states). Finally, it includes a Perform method that does the final calculation. Of course, I’m only showing the declarations for the functions. Listing 1 shows the entire code for the Calculator state machine; after that, I’ll show the base classes that make this all work.

Listing 1 The custom state and driver classes.

#include <string>
#include <iostream>
#include "fsm.hpp"
#include <stack>
#include <queue>
#include <exception>
#include <math.h>

using namespace std;

struct CalcStackItem {
  enum {number, op} itemtype;
  double numbervalue;
  char opchar;
  CalcStackItem(double anumbervalue) {
    itemtype = number;
    numbervalue = anumbervalue;
  }
  CalcStackItem(char aopchar) {
    itemtype = op;
    opchar = aopchar;
  }
};

// Your own driver class that contains
// data available to the state objects.
class Calculator : public FSMDriver {
public:
  queue<CalcStackItem *> PostFixQueue;
  stack<char> OperatorStack;
  FSMState<Calculator> *start;
  Calculator();
  void Run(char *chars, FSMState<Calculator> *StartState);
  double Perform();
};

// State: Start
class StartState : public FSMState<Calculator> {
public:
  StartState(Calculator *adriver) : FSMState<Calculator>(adriver, "StartState") { }
  void OnEntry() {
    cout << driver->getCharString() << endl;
  }

  FSMStateBase *HandleEvent() {
    if (isIn("01234567890.")) {
      return driver->getState("NumberEntryState");
    }
  }
};

// State: NumberEntry
class NumberEntryState : public FSMState<Calculator> {
protected:
  string accum;
public:

  NumberEntryState(Calculator *adriver) :
    FSMState<Calculator>(adriver, "NumberEntryState") { }

  void OnEntry() {
    Append();
  }

  FSMStateBase *HandleEvent() {
    if (isIn("01234567890.Ee")) {
      Append();
      return this;
    }
    else if (isIn("+-*/")) {
      ParseAndPush();
      return driver->getState("OperatorState");
    }
    else if (isIn("=")) {
      ParseAndPush();
      return driver->getState("EqualsState");
    }
    else {
      return driver->getState("ErrorState");
    }
  }

  void Append() {
    accum += Current;
  }

  void ParseAndPush() {
    double x = strtod(accum.c_str(), NULL);
    accum = "";
    driver->PostFixQueue.push(new CalcStackItem(x));
  }
};

// State: Operator
class OperatorState : public FSMState<Calculator> {
protected:
  string accum;
  map<char,int> OpOrder;
public:

  OperatorState(Calculator *adriver) : FSMState<Calculator>(adriver, "OperatorState") {
    OpOrder[’+’] = 0;
    OpOrder[’-’] = 0;
    OpOrder[’*’] = 1;
    OpOrder[’/’] = 1;
  }

  void OnEntry() {
    if (driver->OperatorStack.size() == 0) {
      driver->OperatorStack.push(Current);
    }
    else {
      while (driver->OperatorStack.size() > 0 &&
      (OpOrder[driver->OperatorStack.top()]) >= (OpOrder[Current])) {
        driver->PostFixQueue.push(
          new CalcStackItem(driver->OperatorStack.top()));
        driver->OperatorStack.pop();
      }
      driver->OperatorStack.push(Current);
    }
  }

  FSMStateBase *HandleEvent() {
    if (isIn("01234567890.")) {
      return driver->getState("NumberEntryState");
    }
    else {
      return driver->getState("ErrorState");
    }
  }
};

// State: Equals
class EqualsState : public FSMState<Calculator> {
public:
  EqualsState(Calculator *adriver) : FSMState<Calculator>(adriver, "EqualsState") { }

  void OnEntry() {
    // Finish up grabbing the operators
    while (driver->OperatorStack.size() > 0) {
      char op = driver->OperatorStack.top();
      driver->OperatorStack.pop();
      driver->PostFixQueue.push(new CalcStackItem(op));
    }
    cout << driver->Perform() << endl;
    driver->OperatorStack.empty();
    driver->PostFixQueue.empty();
  }

  FSMStateBase *HandleEvent() {
    if (isIn("01234567890.")) {
      return driver->getState("NumberEntryState");
    }
    else {
      return driver->getState("ErrorState");
    }
  }
};

// State: Error
class ErrorState : public FSMState<Calculator> {
public:

  ErrorState(Calculator *adriver) : FSMState<Calculator>(adriver, "ErrorState") { }

  void OnEntry() {
    cout << " Syntax Error" << endl;
  }

  FSMStateBase *HandleEvent() {
    return NULL;
  }
};

Calculator::Calculator() : FSMDriver() {
  start = new StartState(this);
  new NumberEntryState(this);
  new OperatorState(this);
  new EqualsState(this);
  new ErrorState(this);
}

void Calculator::Run(char *chars, FSMState<Calculator> *StartState) {
  try {
    FSMDriver::Run(chars, StartState);
  }
  catch (StateNameException e) {
    cout << "Invalid state name: " << e.getMessage() << endl;
  }
}

double Calculator::Perform() {

  stack<double> holder;
  CalcStackItem *item;
  double result;
  while (PostFixQueue.size() > 0) {
    item = PostFixQueue.front();
    PostFixQueue.pop();
    if (item->itemtype == CalcStackItem::number) {
      holder.push(item->numbervalue);
    }
    else {
      double second = holder.top();
      holder.pop();
      double first = holder.top();
      holder.pop();
      switch (item->opchar) {
      case ’+’:
        result = first + second;
        break;
      case ’-’:
        result = first - second;
        break;
      case ’*’:
        result = first * second;
        break;
      case ’/’:
        result = first / second;
        break;
      }
      holder.push(result);
    }
  }
  result = holder.top();
  return result;
}

int main(int argc, char *argv[])
{
  Calculator calc;
  calc.Run("10+5-3*2=2*3*4=", calc.start);
  cout << "===============" << endl;
  calc.Run("2*2+3*4=", calc.start);
  cout << "===============" << endl;
  calc.Run("1+2q", calc.start);
  cout << "===============" << endl;
  calc.Run("6.02e23/153.25=", calc.start);
  cout << "===============" << endl;
  return 0;
}

The classes in this file include those that I already mentioned, plus a few other state class that I described in the earlier table.

Now for the framework. This code is actually not very long, but is divided between a header file and a code file. Listing 2 shows the header file.

Listing 2 The state machine header file, fsm.hpp.

#include <string>
#include <map>

class StateNameException {
protected:
  std::string msg;
public:
  explicit StateNameException(const std::string& amsg) : msg(amsg) {};
  std::string getMessage() const { return msg; }
};

class FSMStateBase;

class FSMDriver {
private:
  std::map<char *, FSMStateBase *> States;
protected:
  char Current;
  char *CharString;
  FSMStateBase *CurrentState;
public:
  ~FSMDriver();
  void addState(FSMStateBase *state, char *name) {
    States[name] = state;
  }
  char *getCharString() { return CharString; }
  virtual void Run(char *chars, FSMStateBase *StartState);
  FSMStateBase *getState(char *name) {
    FSMStateBase *res = States[name];
    if (res != NULL) {
      return res;
    }
    else {
      throw StateNameException(name);
    }
  }
};

class FSMStateBase {
protected:
  friend class FSMDriver;
  FSMStateBase() {}
  virtual void OnEntry() = 0;
  virtual FSMStateBase *HandleEvent() = 0;
  char Current;
};

template <typename T>
class FSMState : public FSMStateBase {
protected:
  T *driver;
  char *name;
  friend class FSMDriver;
  FSMState(T *adriver, char *aname) : name(aname), driver(adriver) {
    driver->addState(this, name);
  }
  bool isIn(char* str) {
    return (memchr (str, Current, strlen(str)) >= str);
  }
public:
  virtual void OnEntry() {}
  virtual FSMStateBase *HandleEvent() {}
};

Listing 3 shows the code file, which contains a couple of the methods for the FSMDriver class:

Listing 3 The code for the state machine, fsm.cpp.

#include "fsm.hpp"

FSMDriver::~FSMDriver() {
  // Collect the garbage
  std::map<char *, FSMStateBase *>::iterator iter = States.begin();
  while (iter != States.end()) {
    FSMStateBase *state = iter->second;
    delete state;
    iter++;
  }
}

void FSMDriver::Run(char *chars, FSMStateBase *StartState) {
  int i;
  int len = strlen(chars);
  CharString = chars;
  FSMStateBase *NextState;
  CurrentState = StartState;
  StartState->OnEntry();
  for (i=0; i < len; i++) {
    Current = chars[i];
    CurrentState->Current = Current;
    NextState = CurrentState->HandleEvent();
    if (NextState == NULL) {
      return;
    }
    if (NextState != CurrentState) {
      CurrentState = NextState;
      CurrentState->Current = Current;
      CurrentState->OnEntry();
    }
  }
}

The header file contains four classes:

  • StateNameException is a small exception class. When the driver encounters a name of a state that doesn’t exist, it throws an exception of this class.
  • FSMDriver is the main driver class. To use it, your best bet is to derive a new class from it, as I did in the preceding example; then call addState, passing instances of your state classes. Finally, call its Run method, passing the string of events along with the starting class.
  • FSMStateBase is the base class for all states. It actually serves as a "technicality" because I wanted to create my state class as a template, wherein the template parameter is the driver class. But the driver class contains a map of the state classes, which makes a bit of a circular chicken-and-egg problem. To fix the problem, I started with a non-template base class for the states, FSMStateBase. The driver uses this base class for its members, and the template class is derived from this class, thus solving the problem.
  • FSMState is the base of all the states; as I mentioned, it’s a template that’s derived from the FSMStateBase class. This class includes a pointer to the driver class.

Before moving on, I want to explain just a tad more about the FSMState class being a template class. The reason I made it a template is so that when you derive your classes from it, you can specify your own driver class, thus alleviating the need to do a dangerous downcast. What do I mean by that? Suppose I didn’t use the templates, and instead had two classes like this:

class FSMDriver2 {
public:
  int value;
};

class FSMState2 {
public:
  FSMDriver2 *driver;
};

Now suppose that you derive a class from each of these—your own driver class and a state class:

class MyDriver : public FSMDriver2 {
public:
  int somedata;
};

class MyState1 : public FSMState2 {
  void foo() {
    driver->somedata = 10;
    driver->value = 20;
  }
};

Your driver class contains some data specific to your own state machine. That’s where the problem comes in. Look at how I’m trying to access the data in the state class:

driver->somedata = 10;

That won’t work. You’ll get a compile error because, as far as the compiler is concerned, the driver member points to an instance of the base FSMDriver2 class, even though most likely you created an instance of your derived class and stored its address in the driver variable, like so:

void test() {
  MyDriver dr;
  MyState1 st;
  st.driver = &dr;
}

Really, the driver instance does have a somedata member. But the compiler doesn’t know that. To fix this, you could do a downcast, like so:

class MyState1 : public FSMState2 {
  void foo() {
    ((MyDriver *)driver)->somedata = 10;
  }
};

But that’s considered a dangerous practice because the compiler will create code that forces a cast, even if driver ends up pointing to some class other than MyDriver (that is, to some other class derived from FSMDriver2). Of course, in this code, we know what driver points to, but nevertheless, doing such a cast is considered poor coding practice. You could also use the static_cast operator in C++, but the effect will be pretty much the same.

In addition to being bad coding style, such casts also make the code more cumbersome to use; frankly, it would be a pain to always have to cast the driver member each time you use it. Instead, I decided on an alternative approach—a template. If I use a template, I could simply specify the type when I create the class, and then from there easily access the members. Thus, the short example would turn into this:

class FSMDriver2 {
public:
  int value;
};

template<typename T>
class FSMState2 {
public:
  T *driver;
};

class MyDriver : public FSMDriver2 {
public:
  int somedata;
};

class MyState1 : public FSMState2<MyDriver> {
  void foo() {
    driver->somedata = 10;
    driver->value = 20;
  }
};

void test() {
  MyDriver dr;
  MyState1 st;
  st.driver = &dr;
}

This code compiles and runs. And the cool thing is that I can access members of both my own driver class plus its base class, FSMDriver2, without having to do any casts, as you can see in the foo member function of the state class. And further, since my state class is derived from a template class but is not itself a template class, I don’t need to use templates when I put the class to use, as the test function shows. This template approach is exactly what I did in the framework.

Now I want to give more details about the other template issue, where I created a base class. Continuing with these short sample classes, suppose I want to put a map inside the FSMDriver2 class containing instances of the state classes, something like this:

class FSMDriver2 {
public:
  int value;
  std::map<char *, FSMState2<T> *> States;
};

Of course, this won’t compile, because T doesn’t mean anything inside the FSMDriver2 class. You could fiddle with the class and try it make it work, like this:

template<typename T>
class FSMDriver2 {
public:
  int value;
  std::map<char *, FSMState2<T> *> States;
};

You would just use the same T here as you do in your state classes. But let’s stop there. The reason this won’t work is that the T parameter in this template is ultimately going to be a class derived from FSMDriver2, the very class that’s using T. What a mess. If you search the Web, you might find various workarounds for this problem, but I like the following solution. Instead of trying to coerce the compiler to accept this, remove the templates at this level by making a non-template base class, and use that class inside the driver class:

class FSMStateBase2 {
  int somethingorother;
};

class FSMDriver2 {
public:
  int value;
  std::map<char *, FSMStateBase2 *> States;
};

template<typename T>
class FSMState2 : public FSMStateBase2 {
public:
  T *driver;
};

Now the driver contains a map of states, while the state is a template with the driver as an argument. These three classes compile fine, and this is exactly the approach I used in the real state machine code.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020