Commenting verilog code - best practice? - Page 1
Forum section: electronics / general

author: LeoTech
author_rank: Regular Contributor
timestamp: August 12, 2019, 02:15:48 pm
content: Hello there,Although I have been using verilog for several designs and projects lately, I have no real proper 'education' in verilog nor digital electronics, which means my code and designs often end up being quite a mess - but don't they always?In other words, I have no idea about proper standards and design guidelines, and was wondering about those.As an example, imagine the following code:Code:module how_to_comment(//Some inputs, doesn't matter for the example);//Internal control signalswire RST_wire_in, //Comment section 1CLR_wire_in, //Comment section 1LD_wire_in, //Comment section 1EN_wire_in //Comment section 1;//Structural codeassign RST_wire_in = ....... //Comment section 2assign CLR_wire_in =....... //Comment section 2assign LD_wire_in = ....... //Comment section 2assign EN_wire_in = ....... //Comment section 2endmoduleSo my question is, where in this code would I put the explanation for what each of those signals do, or at least what they are supposed to do?Should they be in section 1 - where they are declared - or in section 2 - where the actual logic takes place?Thanks in advance,Leo

author: NorthGuy
author_rank: Super Contributor
timestamp: August 12, 2019, 02:29:37 pm
content: I write comments when I feel that if I open the code 10 years from now, I may have troubles figuring out things.If I'm afraid that it may not be clear what a signal is, I'll put a comment when the signal is declared.If something I do is not straightforward, I'll put a big comment with explanations why this is done in such a way, and what problems would arise if it's done differently.If it is a long difficult pipeline which is hard to follow, I'll put the detailed description on top.Either way, I'll try to locate comments where it is easier to find them in the future.Most of the time, the code is clear enough by itself, and thus comments are not needed.I don't use Verilog though.

author: SiliconWizard
author_rank: Super Contributor
timestamp: August 12, 2019, 02:48:39 pm
content: I don't use Verilog, but the ideas should be the same.I personally always comment each signal at the "interface" level (that would be ports declaration in VHDL), unless the entity/module is completely trivial and the ports' names are self-documenting.Properly documenting the inputs and outputs of your modules tremendously helps maintenance and code reuse.As to purely internal signals and code, it really depends on the complexity. I rarely comment the role of internal signals, unless there is something particularly not obvious about one and how it's used.Same for code. Comments should be there to help reading and understanding the code, not to state the obvious. I usually put a comment as a kind of title for each process. For the rest, it... depends. I still try and keep this general idea of putting sort of "titles" for each section of code that has a specific purpose (obviously I also group code sections that way). To me it helps readability. It's a bit like reading a book or article. Remove all titles and paragraph separation. Now tell me how readable that is.The key point is to think about readability, reuse and future maintenance. Then stick to a consistent style.

author: Mr. Scram
author_rank: Super Contributor
timestamp: August 12, 2019, 02:52:54 pm
content: Quote from: NorthGuy on August 12, 2019, 02:29:37 pmAssuming I'll still understand what I did later always bites me. I just add comments to everything and anything.

author: NorthGuy
author_rank: Super Contributor
timestamp: August 12, 2019, 03:34:52 pm
content: Quote from: Mr. Scram on August 12, 2019, 02:52:54 pmI still can understand a thing or two in my past code. Sometimes, I even realize that I understand the code better than my comments.

author: colorado.rob
author_rank: Frequent Contributor
timestamp: August 12, 2019, 06:35:55 pm
content: I use comments to describe the specification of a module (I am mostly a software engineer FWIW). Everything needed to specify the external interactions and requirements, timings, etc. Everything that can be formally verified or that one would put into a test bench to verify behavior.Inside the body, comments almost always describe why rather than how. I can always see how -- but the why may not be clear to anyone else needing to maintain it in the future. Module interfaces should follow common names (miso, mosi, sck, and so forth) or use expressive names that make their purpose clear. Nothing wrong with writeEnableA and writeEnableB for RAM modules instead of we_a and we_b. And you need no comments to describe those inputs.In my career as a software engineer I have relied on a triad of documentation, implementation, tests to ensure that the code is well specified, properly designed, and well tested. In the software world we have code coverage reports that allow us to ensure complete coverage. With SystemVerilog, using formal verification, we can use cover() statements to ensure that the behavior of our HDL is well tested. But in general, the HDL tools are 10-20 years behind the software engineering world in terms of development practices and engineering automation.

author: rstofer
author_rank: Super Contributor
timestamp: August 13, 2019, 12:58:26 am
content: What comments? Why do you think they call it code?Seriously, there are good recommendations above.

author: james_s
author_rank: Super Contributor
timestamp: August 13, 2019, 01:06:12 am
content: I've never seen anyone get criticized for putting too many comments in their code. What seems obvious now may not be at all obvious to someone else or even yourself at some later date.

author: NorthGuy
author_rank: Super Contributor
timestamp: August 13, 2019, 01:43:38 am
content: Quote from: james_s on August 13, 2019, 01:06:12 amIt's an optimization task. The time you spend now creating the documentation vs the time you might save later using this documentation. You need to produce just the right amount of documentation which minimizes the combined time expenditure.

author: blacksheeplogic
author_rank: Frequent Contributor
timestamp: August 13, 2019, 02:44:05 am
content: Quote from: james_s on August 13, 2019, 01:06:12 am// Calculate Totaltotal = value * quantity;comment is unnecessary, annoying and code style will be discussed during a code review.// Calculate Totalt = v*qthe comment is more justified but code style will be discussed (for a different reason) during a code review unless t/v/q were a known & expected standard.// Calculate Totalx = y*zthe comment is justified but code style would be discussed during a code review.Note: discussions in code reviews are best avoided.

author: forrestc
author_rank: Unknown
timestamp: August 13, 2019, 06:29:14 am
content: In all code, it's generally a good idea to write a brief summary of the module, for example:Code:// This module implements a 32 bit up/down counter with asynchronous reset.//// Inputs:// clock - The clock for the counter// direction - The direction of the counter. High=increment, low=deincrement// reset - active-high reset of the counter//// Outputs:// out[31:0] - the output of the counter//// The counter will either increment or deincrement the counter by one on the rising edge of the clock pulse, depending on the value of direction.// The counter will reset to zero immediately upon assertion of the reset input and will stay reset while the reset input is held high, even if a clock pulse is received.In my opinion comments beyond that are only necessary if the code is not obvious.

author: SiliconWizard
author_rank: Super Contributor
timestamp: August 13, 2019, 02:12:45 pm
content: Quote from: james_s on August 13, 2019, 01:06:12 amI actually have. But I admit it's a pretty rare occurence. Most developers tend to do the exact opposite out of lazyness.Too many comments can make the code very distracting to read. And yes, some comments can really state the obvious.Imagine something like this:Code:// Increment n by 1.n++;Do you seriously think the comment can be of any use even 20 years later?Do you not think it just makes more lines without any benefit (you just won't see as much code on screen as you could otherwise, which is a pain)?And if you think the above is so ridiculous nobody ever does that, well think again. I've seen that. There are a bit less ridiculous examples of that, such as what blacksheeplogic showed, but the idea is still the same. Comments are not to be used to just state what can be easily inferred from the code itself. Languages have a structure and syntax to convey that (if you use them properly of course: a counter-example could be someone writing horrible obfuscated code and trying to compensate with comments, talk about atrocious).

author: NorthGuy
author_rank: Super Contributor
timestamp: August 13, 2019, 02:44:37 pm
content: Quote from: SiliconWizard on August 13, 2019, 02:12:45 pmWorse yet. If you make comments like this, you may forget to change the comment when the code changes. Then you may end up with something like this:Code:// Increment n by 1.n--;Now the comment is outright harmful. If you syntax highlight is such that comments are more visible than the code, you tend to see the comment and not look at the corresponding code at all. It may take you hours to track this down.

author: SiliconWizard
author_rank: Super Contributor
timestamp: August 13, 2019, 02:51:08 pm
content: That's a general good point.The main problem with comments is of course to keep them up to date. So that can happen for any kind of comment. But obviously when there are too many, and useless ones, the probability increases.Incorrect comments can be harmful in many ways. It can lead to a different developer working on the code, running into a bug which would lead them to believe the comment is correct, and the code isn't, and thus revert back the code to what the comment says (thinking the previous developer fucked up the code), introducing an even more severe bug. It's unfortunately much easier to be tempted to "believe" a comment is right (because it's in natural language) rather than the code itself. I've seen that happening actually!

author: james_s
author_rank: Super Contributor
timestamp: August 13, 2019, 10:26:44 pm
content: My approach is typically to comment at the top of a block of code that represents some logical section of the design. Individual lines may get commented if it is not obvious what they do but it's not necessary to write a novel. Still I would argue that if in doubt, one should err on the side of including more comments, it doesn't take very long to do and it is better to have excessive comments than too few. As with anything it's a balance of cost vs benefit. The more code you write, the better idea you'll gain of what works for you.

author: Mr. Scram
author_rank: Super Contributor
timestamp: August 14, 2019, 01:05:43 pm
content: Quote from: james_s on August 13, 2019, 10:26:44 pmBest practice isn't just what works for you but what also works for others. Especially when more people work on the same code this becomes important.

author: hli
author_rank: Frequent Contributor
timestamp: August 14, 2019, 02:42:33 pm
content: Versioning your code, with not-too-large commits and good commit messages are also helpful. Sometimes just looking at the before-after diff, together with explanation what the intention was help to understand some decisions (e.g. with the 'increment' example from above - probably you can see from the commit when and _why_ its now a decrement, and whether the comment or the code are wrong).

author: james_s
author_rank: Super Contributor
timestamp: August 14, 2019, 03:40:51 pm
content: Quote from: Mr. Scram on August 14, 2019, 01:05:43 pmIf you're doing this for work so you have to care what works for others then your employer will have guidelines you should follow and this discussion is irrelevant.Otherwise do what works for you. I code for myself, I release a lot of it but it's still mine and if someone doesn't like my style that's tough, they're welcome to fork it.

author: jefflieu
author_rank: Contributor
timestamp: August 18, 2019, 10:22:59 am
content: Quote from: LeoTech on August 12, 2019, 02:15:48 pmWow, highschool student playing with Verilog. Nice!. Don't worry, they don't teach you how to comment or how to code in Uni. I don't think the Professors do lots of coding themselves. They're not very concerned about engineering's good practice.Regarding the code comment practice, here's what useful for me when I read someone's code:At the interface if the signals are not some standard one such as axi..wishbone... describe how they behave so that the user of your block doesnt have to dig deeper to figure out. Things like latency, what clock domain the signal is in, is it expected to be single pulse or longer... --> comment so that people can use your block.So i would vote for commenting at the interface itself in stead of in the body where the assignment takes place. Imagine you have more complicated code, I wouldn't want to trace the signals to know how to use the block.In the body, you don't need to comment line by line, comment to describe the idea behind the code ... not very line of codes. I can read code line by line/process by process but its hard to piece together codes to understand the whole idea. Sometimes... just a single line of comment that tells you the gist of it makes a big difference in understanding the code.You should have a clear idea of what you are going to code ... write it down as comment first. That's when you're yourself new to your code. And your comment is useful 5 years down the road or to a new comer.Commenting is also a bit subjective. Some people can write code nicely but they can't comment because they feel everything is obvious from the code, there's nothing to comment, the code say it all. I haven't seen a good practice/guidelines regarding commenting HDL code. It's hard to implement in practice since it's difficult to agree on how one should read/write HDL code. Something obvious to one is not so with the other. If you guys have one at your organisation, please share.Cheers.

author: Bassman59
author_rank: Super Contributor
timestamp: August 18, 2019, 11:51:37 pm
content: Quote from: LeoTech on August 12, 2019, 02:15:48 pmBasically, you need to explain to the reader (and as everyone else has said, that could be you in six months)whyyou are doing something the way you're doing it. The code itself showswhatyou're doing, and well-chosen signal names will give a hint as to their usage.

author: LeoTech
author_rank: Regular Contributor
timestamp: August 19, 2019, 02:18:01 pm
content: Hello Everybody,Thank you all very much for the great advice! Although you don't all agree, and there doesn't appear to be a general set of guidelines, the general consensus appears to be: "As long as you can read it and understand it in five years, and you are not employed in a company, it doesn't matter that much."Your tips and tricks definitely helped, and I will take them into consideration the next time I do some HDL - today probably.I might even make a short list of good practices.Quote from: jefflieu on August 18, 2019, 10:22:59 amWell, as it turns out digital logic, HDL, FPGA and digital electronics in general are far easier to learn by oneself in high school than analog electronics, due to the lag of a higher understanding of both physics and math, but I am working on it.Thanks again everybody,Leo

author: asmi
author_rank: Super Contributor
timestamp: August 19, 2019, 02:57:04 pm
content: Quote from: LeoTech on August 19, 2019, 02:18:01 pmThis is not true, and as you work on "digital" systems, you will see it yourself. Here are few examples:- any "digital" device needs power, and for that you will need linear or switched mode DC-DC converters, and these are very much analog circuits, so unless you pay attention to their analog nature and design accordingly, sooner or later you will encounter converter that will oscillate instead of working properly. Modern converter ICs are becoming progressively more stable in wider range of conditions, but they can never be 100% stable in any circumstances.- the reason you need decoupling caps is exactly because the world we live in is analog, and the power source can't immediately react to a change of your device's power needs.- high-speed transmission lines also need to be designed to take into account analog effects, and the higher the data rate, the more important it becomes.- crosstalk between neighboring traces is often ignored, and it leads to hard to debug problems. For example, signal rise time even for very "pedestrian" SMT32L0 is only 6 ns at highest drive, so for typical 2 layer board it takes just 35 mm of parallel 0.1 wide trace 0.3 mm away from the victim to couple in enough voltage to trip signal to a high (think about reset line going next to a signal trace). This is also analog effect, and I did have a problem of random MCU reset due to crosstalk - trust me, these are no fun to debug. I hope Dave will make a video on this subject at some point to draw more attention to it as a lot of people are either totally unaware of this problem, or think that it only applies to "high speed" lines (which is false).

author: LeoTech
author_rank: Regular Contributor
timestamp: August 19, 2019, 03:06:38 pm
content: Quote from: asmi on August 19, 2019, 02:57:04 pmFair enough, let me re-phrase my statement.Without an extensive math and physics background - at leas more than I have at the moment - it is far easier to grasp the basics of digital electronics than analog electronics. And to play around with it while actually understanding what you are doing and why it works, and not just soldering circuit diagrams you found online together.I am not talking about complete digital systems. I am talking about the basics, like the topics covered in the good 'old' bookDigital Computer Electronics.That book requires far less math and physics compared to the 'classical' beginners guide to analog electronics - namelyThe Art of Electronics.I hope that clears it up,Leo

author: asmi
author_rank: Super Contributor
timestamp: August 19, 2019, 04:05:11 pm
content: Quote from: LeoTech on August 19, 2019, 03:06:38 pmI understand what you're trying to say, my point is that it's only correct to a point.You see - you don't need to quantitatively understand what's going on in a circuit - there is a ton of software that does that for you, what you do need is only a qualitative understanding of analog problems. For example in case of crosstalk, you need to know that every trace emits an EM wave whenever there is a change in current flowing through it, and this wave can induct a current in traces around it, whichmaychange their voltage level enough to temporarily change a signal from one logical level to another. Now, to figure out if thatwillactually happen or not, you can use software to calculate that for you, for example this one:https://www.allaboutcircuits.com/tools/microstrip-crosstalk-calculator/Basically what I'm saying is you need to be aware of these effects and when theycanbe a problem, but to find out of theywillbe a problem you can use software. Formulas are only required for the latter part - and by using software you can leave figuring them out to somebody else, the former doesn't need them so much (or they might be very simplistic as they only need to illustrate a point).

author: tggzzz
author_rank: Super Contributor
timestamp: August 19, 2019, 04:51:04 pm
content: Quote from: LeoTech on August 19, 2019, 02:18:01 pmGood for you, and have fun.A few observations about comments inanylanguage.Good comments are an art, and developing "good taste" helps.It is always possible (with difficulty) to work outwhatsomething is doing by reading the code, so arguably there's no need to put that in comments.Reading the codedoesn'tlet you understand:whythe is doing thatwhy it doesn't do the same thing adifferentway, e.g. a different algorithm or structurewhat are thelimitsor boundary cases that the code addresses and avoidsso putting those points in the comments can be helpful.The other point is that with a large implementation, it is important to be able toquicklywork out which bits of code youdon'tneed to understand. Good overall structuring and comments help there.BTW, unless you are working with femtoamps, are photon counting, or are in the Z-domain, everythingisanalogue. Typical "digital" circuits are merely overdriven analogue circuits thatinterpretvoltages/currents as being digital. Poor quality analogue inputs can be interpreted incorrectly. There's a whole important field called "signal integrity".