- Create a enumerated type that corresponds to each of the states. The terminal states will be returned as symbol.
enum Symbol {Zero,InLess,InGreater,Error, Less,NotEqual,LessEqual,Equal,Greater,GreaterEqual};
- Initize the states. For example Zero will have one exit to InLess (1), InGreater(2), Equal(7) and Error(3). Notice the white space keeps you in state zero.
Exits exits;
exits.insertItem(Exit(' ',Zero));
exits.insertItem(Exit('\t',Zero));
exits.insertItem(Exit('<',InLess));
exits.insertItem(Exit('=',Equal));
exits.insertItem(Exit('>',InGreater));
state[Zero] = State(exits.numberInArray(),exits.copy() );
//Clear before creating the next state
exits.clearArray();
- Finally, in this case getNextSymbol needs only more from state to state until a terminal state is achieved. If you were accumulating a value such as a number or string, you would have special conditions that would record information if you were in a state that was an appropriate internal state, such as InIdent for an identifier.
Symbol LexAnalizer::getNextSymbol()
{
id = "";
Symbol currentState=Zero;
do {
currentState = state[currentState].nextState(ch); //get the next state
}while (currentState<Error && ch !=0);//Error is the first terminal state
if (ch ==0) //Ran out of source code
return Error;
return currentState;
}