It's nothing magical really, I just read the cfg, ctrlr and ini files for the game loaded, so I would have two bits of data, the control description (aka the label/text) and the button/key/whatever it's mapped to according to the files. So now you have that. Then there is a separate document defining the users control panel layout that doesn't really have anything to do with controls.dat. It has a bunch of labels, with each label having a button/key/whatever and a position on the graphic. Now you just compare the two files.... Since they both have a button/key/whatever defined, you just apply the control description to any control panel label that matches the key determined in the controls.dat data.
Of course I'm over-simplifying. The viewer also checked various settings within mame, so that... let's say some of your control panel labels are mapped to the mouse, and you don't have the mouse enabled in mame, those labels are left blank. In addition there was an order in which the cfg/ctrlr/ini files has to be read as they override each other in mame. There's a ton of other little things that were read in, some hard-coded control constants that mame won't print out on cfg files, ect. It was actually quite a hassle to get things working right, which is why it'd make more sense to get the data inside mame itself.... no more mucking about through half a dozen cfg files to determine how mame has a particular control mapped. I would go into further detail, but mame has changed a lot since the last version of johnny 5, so a lot of my info isn't going to apply anymore.