Search code examples
ccompiler-constructiontransitiondiagramlexical

How Do You Create A Transition Diagram Based on C Code


I have to create transition diagrams for a lexical analyzer for the identifiers and numbers.

The code is included below:

/* recursive factorial function */
int fact (int x )
{ 
   if (x>1)
      return x * fact (x-1); 
   else 
      return 1; 
} 

void main (void)
{
    int x;    
    x = read(); 
    if (x > 0) write (fact (x)); 
} 

I am feeling a little lost on how to create this diagram. Can anyone point me in the right direction or include resources that may help me with this task?


Solution

  • The lexer starts off in a null or initial state. It hits the "i". So it knows it must have either a keyword or an identifier. It hits the 'n' and the 't' and adds them to the token. it hits the space. So it knows that's the end of the token, which is "int", a keyword. Now it hits the 'f'. Same story, but the token is "fact", that's not a keyword, so it's an identifier. Now the '(' - that's an open parenthesis token. So it goes on.

    When it hit's the '/' that could be either a division token or the start of a comment, in fact it's the start of a comment. So it now goes into comment state until it hits the */.

    There's nothing else significantly different, except that you have a few integer literal tokens in there. To make it easy for you, there are no strings. main is a bit of a special case, depending how the lexer is written, it could be regarded as a keyword or a plain identifier.