2 ms·
They're not really type annotations (because Forth is still basically untyped), but stack effect annotations. They're just a comment in parentheses that tells h
by benhoyt 4y ago
They're not really type annotations (because Forth is still basically untyped), but stack effect annotations. They're just a comment in parentheses that tells human readers of the code how many items are consumed/produced and (very roughly) what type they are:
: SQUARE ( n1 -- n2 ) DUP * ;
I've never run into any checkers for these comments -- though https://stackoverflow.com/a/40321950/68707 https://stackoverflow.com/a/40321950/68707 indicates that checkers may exist. For example, Gforth (GNU Forth), one of the most popular and full-fledged Forth compilers doesn't do this.
- TapamN 4y agoStrongForth (http://www.arestlessmind.org/2009/02/03/intro.html http://www.arestlessmind.org/2009/02/03/intro.html) is a statically typed Forth that checks (and requires!) the annotations. It traces how the stack changes after every operation, and guarantees that every function is passed the correct number and types of parameters, and leaves the correct parameters on the stack when it returns. It's impossible to underflow the stack, and overflows are as likely as in C/C++/etc. To do this, there are some limitations on how the stack can be used compared to regular Forth. (For example, both sides of an IF/ELSE must leave the same number of items on the stack with the same types, but they can have different values. An IF without an ELSE can never change the depth of the stack or what types are on it, since the implicit, empty ELSE side says that the stack doesn't change.) This generally isn't a huge problem, as the things you can't do in StrongForth are usually not such a good idea from a maintenance perspective in regular Forths.