BusPirate / Bus_Pirate

Community driven firmware and hardware for Bus Pirate version 3 and 4
625 stars 130 forks source link

RFC: Refactor to use constant expressions instead of ifdefs #99

Open andersm opened 6 years ago

andersm commented 6 years ago

This is an RFC for an idea I mentioned at at some point, reducing the amount of ifdefs in favour of constant expressions and dead code elimination. There's some ugly compatibility dummy definitions that could maybe be abstracted away, and the string generation would need reworking to automatically create the dummy definitions, but the main point is to see if anyone else thinks this would be a good idea.

Code size comparison, tested with XC16 1.35: BPv3: +9 bytes, BPv4: no change

JarrettR commented 6 years ago

This is really good for readability

agatti commented 5 years ago

Apologies for taking this long to check this out. I'm personally partial to #defines due to habit, although #defines should not really increase code size. Whilst for v4 boards there's plenty of ROM space to use, v3 boards can be a bit more strapped for empty space to fit things in.

@andersm can you please check if there's a way to get the compiler to not increase code size using if-blocks? In theory, if a symbol is already defined the branch block that cannot be taken should be eliminated in an early compilation pass so I wonder why you see a code size increase, after all.

andersm commented 5 years ago

I believe the code size increase comes from the case label on line 825, which is behind an #ifdef BUSPIRATEV4.

agatti commented 5 years ago

I see. I am still not 100% sure on whether having two separate ways to split code could help, as there are quite a few #define entries that vary depending on the board type (think pin definitions). Any ideas on how to sort that out in a way that does not increase project complexity?

andersm commented 5 years ago

Defining macros for pin names is a good thing, since it abstracts away the hardware differences and makes the code easier to read.

Another strategy for reducing the number of #ifdefs is to extract the blocks into inlinable functions, separated by board type. It does mean the compiler can't check both branches of the code in one go, but can increase the readability a lot.

agatti commented 5 years ago

The inlinable functions way sounds more like it - I've started doing something like that for the board hardware definition in c93d03286c5e5fd8417ea6108d088fbb57972371, actually (still not finished yet, help is as usual welcome).