Complex designs are built by nesting modules in a hierarchy:
// Level 3: Basic gates
module and_gate (input a, b, output y);
assign y = a & b;
endmodule
// Level 2: Half adder using gates
module half_adder (
input wire a, b,
output wire sum, carry
);
xor u_xor (sum, a, b); // Built-in primitive
and_gate u_and (.a(a), .b(b), .y(carry));
endmodule
// Level 1: Full adder using half adders
module full_adder (
input wire a, b, cin,
output wire sum, cout
);
wire s1, c1, c2;
half_adder u_ha1 (.a(a), .b(b), .sum(s1), .carry(c1));
half_adder u_ha2 (.a(s1), .b(cin), .sum(sum), .carry(c2));
or u_or (cout, c1, c2);
endmodule
// Top: 4-bit ripple carry adder
module adder_4bit (
input wire [3:0] a, b,
input wire cin,
output wire [3:0] sum,
output wire cout
);
wire [3:0] c; // Internal carries
full_adder fa0 (.a(a[0]), .b(b[0]), .cin(cin), .sum(sum[0]), .cout(c[0]));
full_adder fa1 (.a(a[1]), .b(b[1]), .cin(c[0]), .sum(sum[1]), .cout(c[1]));
full_adder fa2 (.a(a[2]), .b(b[2]), .cin(c[1]), .sum(sum[2]), .cout(c[2]));
full_adder fa3 (.a(a[3]), .b(b[3]), .cin(c[2]), .sum(sum[3]), .cout(cout));
endmodule