title: Generate If Statements in Verilog
body: <p>I'm trying to create a synthesizable, parametrized priority encoder in Verilog. Specifically, I want to find the least significant 1 in a vector and return a vector containing just that 1. For example:</p>
  
  <pre><code>IN[3:0] | OUT[4:0]
  --------+---------
  1010    | 00010
  1111    | 00001
  0100    | 00100
  0000    | 10000   (special case)
  </code></pre>
  
  <p>So if the vectors are four bits wide, the code is:</p>
  
  <pre><code>if (in[0]==1'b1) least_one = 1;
  else if (in[1]==1'b1) least_one = 2;
  else if (in[2]==1'b1) least_one = 4;
  else if (in[3]==1'b1) least_one = 8;
  else out = 16; // special case in==0, set carry bit
  </code></pre>
  
  <p>I need a general, scalable way to do this because the input/output vector length is parametrized. My current code is:</p>
  
  <pre><code>module least_one_onehot
  #(parameter ADDR_WIDTH=4)
  (output reg [ADDR_WIDTH:0] least_one,
  input [ADDR_WIDTH-1:0] in);
  
  genvar i;
  
  always @(in) begin
      if (in[0]==1'b1) least_one = 1;
      generate for (i=1; i&lt;ADDR_WIDTH; i=i+1) begin : U 
          else if (in[i]==1'b1) least_one = 2**i; 
          end 
          endgenerate
      else least_one = 2**ADDR_WIDTH;
      end
  
  endmodule
  </code></pre>
  
  <p>When I try to compile this, I receive the following errors:</p>
  
  <pre><code>file: least_one_onehot.v
          generate for (i=1; i&lt;ADDR_WIDTH; i=i+1) begin : U
                 |
  ncvlog: *E,GIWSCP (least_one_onehot.v,10|8): Generated instantiation can only be valid within a module scope [12.1.3(IEEE 2001)].
                          else if (in[i]==1'b1) least_one = 2**i; 
                             |
  ncvlog: *E,NOTSTT (least_one_onehot.v,11|6): expecting a statement [9(IEEE)].
                  endgenerate
                            |
  ncvlog: *E,GIWSCP (least_one_onehot.v,13|12): Generated instantiation can only be valid within a module scope [12.1.3(IEEE 2001)].
                  else least_one = 2**ADDR_WIDTH;
                     |
  ncvlog: *E,NOTSTT (least_one_onehot.v,14|5): expecting a statement [9(IEEE)]
  </code></pre>
  
  <p>I've tried various arrangements of the generate, if, and always statements, all without success. Anyone know the proper syntax for this? Case-statement implementation or other alternatives would also be fine. Thanks.</p>