Enumerating FSM states automatically for Verilog with Perl

This post was written by eli on April 13, 2010
Posted Under: FPGA,perl,Software

Having a pretty large state machine, I wanted the states enumerated automatically. Or at least not do the counting by hand. I mean, doing it once is maybe bearable, but what if I’ll want to insert a new state in the future?

So what I was after is something like

module main_state #(parameter
		    ST_start = 0,
		    ST_longwait1 = 1,
		    ST_longwait2 = 2,
		    ST_synthesizer = 3,
		    ST_synth_dwell = 4)

to support a state machine like

	case (state)
	  ST_start:
	    begin
	       state <= ST_longwait1;
	       reset <= 1;
	    end 

	  ST_longwait1:
	    begin
              (...)
	    end

and so on.  Only with more than 20 states.

The solution is short and elegant. At command prompt (DOS window for unfortunate Windows users), this simple Perl one-liner does the job.

perl -ne 'print "$1 = ".$i++.",\n" if /^[ \t]*(\w+)[ \t]*:/;' < main_state.v

where main_state.v is the Verilog module’s file, of course. The script looks for anything textual which starts a line and is followed by a ‘:’. This is not bulletproof, but is likely to work. The output should be a list of state number assignments, which you can copy-paste into the code.

So this script will work only if there’s a single case statement in the input, which is the Verilog module itself. If there are several, just copy the relevant case statement into a separate file, and put that file’s name instead of main_state.v in the example above.

If you happen to be impressed by the magic, then you should probably take some time to play around with Perl. Every minute spent on that will be regained later. Believe me.

And if you don’t have Perl on your computer, that surely means you have a bad taste for operation systems. There are two possible ways to come around this:

  • If you have Xilinx ISE installed on your computer, try writing “xilperl” instead of “perl” above. xilperl is just a normal Perl interpreter, installed along with the Xilinx tools.
  • Download Perl for your operating system. It’s free (as in freedom) software, so there is no reason why you should pay a penny for this. There are many sources for Perl. I gave the link to ActivePerl, which is the one I happen to know about.

Add a Comment

required, use real name
required, will not be published
optional, your blog address