Skip to content

Instantly share code, notes, and snippets.

@tangentstorm
Last active December 11, 2015 11:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tangentstorm/4592672 to your computer and use it in GitHub Desktop.
Save tangentstorm/4592672 to your computer and use it in GitHub Desktop.
Talk about "build one to throw away"
## OBERON SYNTAX TO COMPILE:
FOR x := start TO goal BY step DO
block
END;
## StringTemplate ( generating retro code ):
for_stmt(id, beg, end, step, block) ::= <<
( FOR ) <id>
( := ) <beg>
( TO ) <end>
( BY ) <step>
( DO
[
<block>
]
( END ) FOR
>>
## Retro helper macro
( -- for-loop compiler -------------------------------- )
{{ ( helper functions )
: relop ( n-q : given the step, pick correct comparison op )
0 > [ ' <= ] [ ' >= ] if ;
: lit,, ( n- : pops number off stack and writes it as a literal )
1 , , ;
---reveal---
( main routine )
: FOR "( besq- ) compile a FOR loop, given begin, end, step, and (n-) quote" :doc
immediate ( COMPILE-TIME )
push ( besq- | -q ) ( RUN-TIME )
rot ( bes-esb ) ( ----------------------------------- )
lit,, ( esb-es ) ( -n : n := begin )
[ [[
pop lit,, ( es-es | q- ) ( n-nq : address of quote )
` sip ( nq-n : run block, preserve counter )
( | a TO z BY +x | z TO a BY -x )
( | -------------|------------- )
dup lit,, ` + ( n-n : n += step | n -= step )
` dup relop lit,, ` do ( n-nf : n <= goal? | n >= goal? )
]] ]
` while ( q- : loop until the quote returns 0 )
` drop ( n- : drop the loop var )
;
}}
### Conclusion : NO THANK YOU!
The above code took several hours to write.
It was educational, but what a complete mess!
I'm not even going to try and run it.
What I should have done is implement simple IF and WHILE macros
first, and then build the FOR loop compiler out of those pieces.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment