Skip to content
code0.HDL

06Implementation

Guard an unused payload with valid

Problem

decodeCommand returns a Decoded record containing valid and payload. Codes 3'd0 through 3'd3 are legal and must produce 8'h11, 8'h22, 8'h44, and 8'h88. Codes 3'd4 through 3'd7 are illegal, but the current default arm incorrectly returns valid: True for them.

The record defines a validity protocol: payload carries information only when valid is True. The type does not enforce that rule, so producers and callers must both honor it.

Read the starter

Follow each case arm into both fields. The four explicit arms already satisfy the legal-result contract. Only the default arm is editable for this task.

mkTop is a fixed public harness. It observes adjacent boundary values: legal code three, including its payload, and illegal code four, using only its validity flag. Keep this server-owned suffix unchanged.

Predict before editing

For code four, predict why valid == True lets a caller treat the fabricated zero as a command. Identify the condition under which payload must not be inspected.

Make the smallest change

  • Preserve every legal code and payload mapping.
  • Return valid == False for all four illegal codes.
  • Do not make any behavior depend on an invalid payload.

A ? payload is idiomatic because it states that the value is irrelevant and lets the compiler choose an implementation. A fixed payload such as zero is also behaviorally correct when valid is False: the contract assigns no meaning to those bits. Correctness comes from the flag and from callers not observing invalid payloads, not from a particular spelling or bit pattern.

Run and explain

Run the corrected source. Code three must report valid=1 and payload 88; code four must report only valid=0. Explain why printing or comparing the second result's payload would violate the same contract that makes ? safe.

Completion check

  • Codes zero through three remain valid with their original payloads.
  • Codes four through seven are all invalid.
  • No caller reads, prints, compares, or otherwise uses payload after seeing valid == False.

Progressive hints and concept

Hint 1

The bug is in the field that tells a caller whether the other field may be used.

Hint 2

The default arm covers exactly the four codes outside the legal range.

Concept

A don't-care is safe at a protocol boundary only when control information prevents every observer from depending on it. Here valid carries that control information; it does not physically hide payload.

Extension experiment

On paper, replace the invalid payload with two different concrete constants. Predict the caller's valid/invalid decision in each case without reading or printing the invalid payload. Explain why changing those bits must not change the protocol result. Keep the fixed mkTop unchanged.

Review this concept
Ready
Main.bsv