Watching Code
Tuesday, December 3, 2024
Factor has a watching words feature that allows you to see the inputs and outputs of a word when it is called. I have wanted a way to define a watched code block that we could use to see the stack before and after some inner part of a word.
It turns out that it’s pretty simple to make this syntax using our existing watch implementation from the tools.annotations vocabulary:
DEFER: WATCH>
SYNTAX: <WATCH
\ WATCH> parse-until >quotation dup (watch) append! ;
Using this, we can now watch the inner part of a word, for example this word that increments the input by 1:
: foo ( x -- y ) 1 <WATCH + WATCH> ;
And see it used:
IN: scratchpad 10 foo
--- Entering [ + ]
x 10
x 1
--- Leaving [ + ]
x 11
--- Data stack:
11
One thing that I’d like to improve on this someday, is making it so this watch syntax has a prettyprint implementation that allows it to be rendered as it is typed.
I have added this to the latest developer version if you’d like to update and give it a try!