Juha,
On occasion I've wanted such a thing too, but never looked into it.
>From the emacs lisp Info on "Keyboard Macros", their definition is controlled by the variable defining-kbd-macro which comes from the C code. So, that would be the place to look.
I find it (defining_kbd_macro in C) in keyboard.c and macros.c. It only appears 18 times, so it shouldn't be *too* hard to copy or mimic or modify to meet your needs. You'd also have to consider doing corresponding work with kmacro.el (and maybe other places too).
With respect to editing: "C-x C-k e runs the command edit-kbd-macro,...."
You can save that definition and do whatever you need to with it. Indeed, the annotations in the keyboard macro editor generally give enough good hints that you could convert it into LISP, which would let you do very general programming with it.
I hope this helps.
,Doug
Afterthought: By "*too* hard" I mean that I'm guessing it would take under a week of full time development. It might be a few hours, but I've never touched emacs' C code.
I didn't see anything like this in the emacs TODO list. Perhaps you could make a feature request to
bug-gn...@gnu.org.