52Implementation
Pass a polymorphic vector width
Problem
A polymorphic BDPI import would receive its vector through a pointer and get no
automatic width, so this design keeps the C function concrete:
foreignWidth takes one 8-bit width. The polymorphic BSV helper vectorWidth
must supply that width for each Bit#(n) type used by the adapter. The starter returns zero for
every type, so the public run prints width = 0 for a 17-bit value.
Change only the body of vectorWidth. Keep its signature, the interface with
its three methods, the adapter, the foreign-function declaration, and mkTop.
Read and predict
- Read
vectorWidth's signature. The width lives in the type parametern, not in the argument's bits. - Read
mkWidthAdapter. The same definition is used at three types:Bit#(5),Bit#(17), andBit#(31). Each use fixesnseparately. - Before pressing Run, predict the result for each of the three widths, and
explain why the argument's bit pattern cannot answer the question:
17'h0and17'h1ffffhave the same width.
Make the repair
Turn the type-level number into a value, then convert it to the 8-bit result. Replace only the returned expression, run the 17-bit public path, and then reason through the other two instantiations without running them.
Completion contract
vectorWidthreturnsnas an 8-bit value for the adapter's widths 5, 17, and 31.- All values of one type produce the same width, whatever their bits.
- The three adapter methods report 5, 17, and 31.
- Returning
17as a constant matches only the public sample.
Progressive hints
Hint 1: where the width is
The width belongs to the type parameter, not to the function argument's bits. It is known during elaboration, before any value exists.
Hint 2: from type to value
BSV has a function that turns a numeric type into an Integer. Apply it to
n, then convert the Integer to the declared result type.
Transfer experiment
Call one adapter method with all zeros and then with all ones. Predict why both report the same width before running, then restore the original call.