The code is in
repeat.el. See command
repeat, which is what
C-x z is bound to.
The code uses the fact that Emacs records the current command and the last command in variables. The
repeat code resets the variable
this-command to what it records as the command that was previous to command
Note that you can define your own repeatable command by using code such as this:
(defun my-repeat-command (command)
(let ((repeat-previous-repeated-command command)
(defun some-command (...)
(defun some-command-repeat ()
"Invoke `some-command' in a repeatable way."
repeat does kind of "remap the key" on the fly. It uses
set-transient-map, defining the key in a transient map, and then it calls itself again.
Prior to Emacs 24 it didn't use a new (transient) keymap (such a thing didn't exist as such back then). It just checked whether the next key/command was the same as the last.
repeat fools Emacs into thinking that the current command is whatever command was used last.