<p>What level of static typing can be added to a stack-based language? I know it's impossible to fully statically type some stack languages:</p>
<pre><code>&quot;string&quot; 399 1 io.inputAsInt range loop swap end-loop # can't determine what'll be on the top of the stack until runtime
</code></pre>
<p>But is there some level of static typing that stack languages can have?</p>

<stack><static-typing>
How to Add Static Typing to a Stack Language?
CC BY-SA 4.0
2023-05-17T23:30:41.627Z
Could you "evaluate" the user's code by pushing and popping types (instead of values) at compile time? That would let you follow what kind of data exists.
chrisaycock
CC BY-SA 4.0
2023-05-17T23:31:48.767Z
But that falls apart once you enter something like a for loop or a while loop where the number of loops can't be determined at compile time
lyxal
CC BY-SA 4.0
2023-05-17T23:52:05.750Z
[Kitten](https://kittenlang.org/) is a statically typed stack-based language.
alephalpha
CC BY-SA 4.0
2023-05-17T23:54:01.887Z
But it's fairly easy to construct a stack-based language that is fully statically typed, it just means you can't write the sorts of programs that you can't type, so I think the premise is a bit underspecified here.
Michael Homer
CC BY-SA 4.0
2023-05-18T01:36:21.823Z
@lyxal You can type check the loop body, and simply disallow this kind of loops. If you really want to allow loops that may return different types, you can use a union type.
alephalpha
CC BY-SA 4.0
2023-05-18T03:24:30.460Z
Your assertion that "it's impossible to fully statically type a stack language" is surely false, and what your example shows is that dynamically typed stack languages, like other dynamically typed languages, allow for code which would be difficult or unfeasible to write static types for ─ all this says is that statically typed languages don't allow every kind of code that dynamically typed languages allow, which is true in every paradigm.
kaya3
CC BY-SA 4.0
2023-05-18T03:27:27.567Z
As for the question, *"What level of static typing can be added to a stack-based language?"*, I imagine that a whole PhD thesis on this subject could establish a lower baseline for how much static type safety can be conveniently integrated into a stack-based language, so this is kind of a research question. I recall reading a paper on row polymorphism for static typing of stack effects, a few years ago, so perhaps what you're looking for is a summary of the state of the art, rather than a definitive answer?
kaya3
CC BY-SA 4.0
2023-05-18T03:27:36.980Z
@kaya3 the stack language(s) I'm thinking of wouldn't be easy to add too, but I do see that without certain constructs it's as simple as it would be for a more conventional language. I've edited the question accordingly.
lyxal
CC BY-SA 4.0
2023-07-12T03:36:23.770Z
There is a [Strongly-Typed Forth called StrongForth](https://www.stephan-becher.de/strongforth/).  Between Factor, Kitten, and StrongForth, the statement in your question misleads  --  You say "But is there some level of static typing that stack languages can have?" and the answer is "Yes. Completely." Please fix your misleading question!
MicroservicesOnDDD
<p>I'll complement Michael's excellent answer with some examples from an existing stack-based compiled language <a href="https://factorcode.org/" rel="noreferrer">Factor</a>.</p>
<p>Factor has one primary type system: <a href="https://docs.factorcode.org/content/article-inference.html" rel="noreferrer">stack effects</a>. A stack effect of a function describes how many items it consumes and/or produces on the stack. Every defined function in Factor is annotated with its stack effect, which is checked during compilation.</p>
<p>A typical function looks like this:</p>
<pre><code>: add ( x y -- z )
  &lt;function-body&gt; ;
</code></pre>
<p>This <code>add</code> function takes two items on the stack, and produces one.</p>
<p>As a more involved example, the following function <code>loop</code> takes a &quot;quotation&quot; (a statically checked lambda) and repeatedly runs the quotation until it produces an <code>f</code> (false value) on the top. Here, <code>...</code> means that the function can consume any number of stack items in addition to the parameter <code>pred</code>, but the stack height of <code>...</code> part must be preserved. In addition, the quotation parameter <code>pred</code> is also checked for its own stack effect at the call site.</p>
<pre><code>: loop ( ... pred: ( ... -- ... ? ) -- ... )
  &lt;function-body&gt; ;
</code></pre>
<p>One could add static typing on the stack items themselves on top of stack effect checking. Factor already has <a href="https://docs.factorcode.org/content/word-TYPED__colon__,typed.html" rel="noreferrer">a rudimentary tool</a> for basic typing of this kind, but it can be extended much further.</p>
<p>For example, the <code>swap</code> function (a primitive that swaps two top items) could be typed with two generic type parameters, like <code>( 't1 't2 -- 't2 't1 )</code>.</p>
<p>For the <code>loop</code> above, one could impose an extra constraint on the <code>...</code> part: if it consumes <code>n</code> items of type <code>t1, t2, ..., tn</code> respectively, it must output <code>n</code> items of the same types as well. This is analogous to &quot;variadic generics&quot; where the number of generic parameters itself can be generic over integers.</p>
<p>Without automatic union types (as Michael suggested), OP's program won't typecheck because <code>'t1 't2</code> will be inferred to be <code>int string</code> and <code>[int string] != [string int]</code>, which violates the expected <code>( ... -- ... )</code> type of loop body.</p>
<p>Other than stack effects and stack element type matching, there is nothing much different from non-stack languages in terms of typing, so you can employ pretty much any type system that works for you. This is also mentioned in Michael's answer, but to reiterate, ultimately there's no difference between trying to type</p>
<pre><code>123 &quot;abc&quot; [ swap ] read-int times
</code></pre>
<p>in Factor and</p>
<pre><code>a = 123
b = &quot;abc&quot;
n = int(input())
for _ in range(n):
    a, b = b, a
</code></pre>
<p>in Python.</p>

CC BY-SA 4.0
2023-05-18T04:40:03.513Z
2023-05-18T04:40:03.513Z
Bubbler
<p>I said in the comments that I had some disagreement with the premise of the question, but let's dive into why that is. Fundamentally, I think a fully statically typed stack language is eminently possible, and all the trade-offs in doing that are relevant to other paradigms as well.</p>
<hr />
<p>We can easily define a (non-trivial) sound static type system for the language in your example. One of the rules will be that the body of a loop must complete with the same stack type as it began. It will reject your program as badly-typed, and you'll need to change it. For other functions, it will simulate their stack effects in the obvious way, pushing and popping representations of types to a stack, and reject the program when the stack doesn't meet the function's requirement.</p>
<p>This is a sound static type system and checker. It will reject some programs that perhaps could have run, but that's what all sound static type checkers do. It will allow plenty of programs through, and maybe enough to be useful.</p>
<p>Perhaps we do want this program to run. We could extend the type system: the loop construct is deemed to produce a union type of all possible results¹, and now this program is accepted!</p>
<p>The next question, though, is what we can do <em>after</em> that if we continue the program. We know that what's on top is either an integer or a string, but not which; we should be able to call a function that accepts both of those (perhaps a <code>print</code>, or a rotation), we should be able to drop or duplicate it, and we should be able to push new values onto the stack on top of it.</p>
<p>We can't do anything that requires <em>specifically</em> an integer or <em>specifically</em> a string as an argument, <strong>but that's correct — the program would crash</strong> some of the time, and that's exactly what a static type system is there to save us from. The language could provide a construct for inspecting the dynamic type — an <code>is-int</code> returning a boolean perhaps, or a pattern-matching system branching on different types. That would be fine to do, and the type system can accommodate these extensions as well.</p>
<p>Perhaps this isn't the language you want to have, which is fine and reasonable, but it's still a stack-based language and it's fully typed. There's nothing particular to a stack language about the complications we're facing here — the sample program is no different to</p>
<pre class="lang-none prettyprint-override"><code>x = 399
y = &quot;string&quot;
for i from 1 to io.inputAsInt:
   x, y = y, x
</code></pre>
<p>We can't determine what type y is here either! A type system for <em>this</em> language would likely also reject the program, or leave us with a union type, and many of the same solutions apply. Just like the example program, this has clear semantics and could run safely to the end in an untyped model.</p>
<hr />
<p>Now, there <em>are</em> some cases where stack-based languages really are a little different: where the stack is actually the material element. The obvious case is something like <code>1 io.inputAsInt range loop drop end-loop</code>: we don't know which items are left afterwards, or whether it went off the stack. This program would <em>also</em> be rejected by the type system sketched above, probably even after the extension. Arguably, that's what you want a type system to do for you.</p>
<p>This though is exactly the same problem as running off the end of an array in a procedural language, and it also admits of similar fixes: stack types that incorporate the stack size, rejecting programs that don't validate the change they're going to make, bounded stacks, and so on. All of these tools are available to the language designer, and it's up to them which programs they want to eliminate and where they want to spend their complexity budget to ameliorate it. They also have plenty of options for filling in that lost expression space, like adding more compound types or reified stacks.</p>
<p>Most statically-typed concatenative languages do reject programs like that, at least by default, in favour of having explicit bounds on the stack transformation that a function can do. We can include in that category things like Java bytecode, which is typed and verified before it runs, as well as human-directed programming languages like Kitten.
<strong>It's fine for a language to decide it wants an <em>unsound</em> type system instead</strong> that lets some of these cases through, and there are plenty of deliberately unsound languages in other paradigms too. The unsound system can still perform useful validations and be worthwhile.</p>
<p>For a short formal treatment of typing concatenative languages you can look at <a href="https://repository.library.northeastern.edu/files/neu:4f186p17k/fulltext.pdf" rel="nofollow noreferrer">Robert Kleffner's thesis</a>, which also points at earlier work on stack effects in Forth in particular.</p>
<hr />
<p>¹ This is actually somewhat complicated to do precisely, since there is a dependency between the two types at the top (if one is a string, the other isn't), but it is resolvable, or we can just say the top two entries are typed <code>int|string</code>. It doesn't matter for the moment and so I'm going to ignore that.</p>

CC BY-SA 4.0
2023-05-18T02:42:25.710Z
2023-05-21T08:43:59.013Z
2023-05-21T08:43:59.013Z
Michael Homer
# How to Add Static Typing to a Stack Language?
Posted by: username_0 on 2023-05-17
What level of static typing can be added to a stack-based language? I know it's impossible to fully statically type some stack languages:
"string" 399 1 io.inputAsInt range loop swap end-loop # can't determine what'll be on the top of the stack until runtime

But is there some level of static typing that stack languages can have?
**Tags:** stack static-typing
> **Comments:**
> **username_1**: Could you "evaluate" the user's code by pushing and popping types (instead of values) at compile time? That would let you follow what kind of data exists.  
> **username_0**: But that falls apart once you enter something like a for loop or a while loop where the number of loops can't be determined at compile time  
> **username_2**: [Kitten](https://kittenlang.org/) is a statically typed stack-based language.  
> **username_3**: But it's fairly easy to construct a stack-based language that is fully statically typed, it just means you can't write the sorts of programs that you can't type, so I think the premise is a bit underspecified here.  
> **username_2**: @lyxal You can type check the loop body, and simply disallow this kind of loops. If you really want to allow loops that may return different types, you can use a union type.  
> **username_4**: Your assertion that "it's impossible to fully statically type a stack language" is surely false, and what your example shows is that dynamically typed stack languages, like other dynamically typed languages, allow for code which would be difficult or unfeasible to write static types for ─ all this says is that statically typed languages don't allow every kind of code that dynamically typed languages allow, which is true in every paradigm.  
> **username_4**: As for the question, *"What level of static typing can be added to a stack-based language?"*, I imagine that a whole PhD thesis on this subject could establish a lower baseline for how much static type safety can be conveniently integrated into a stack-based language, so this is kind of a research question. I recall reading a paper on row polymorphism for static typing of stack effects, a few years ago, so perhaps what you're looking for is a summary of the state of the art, rather than a definitive answer?  
> **username_0**: @kaya3 the stack language(s) I'm thinking of wouldn't be easy to add too, but I do see that without certain constructs it's as simple as it would be for a more conventional language. I've edited the question accordingly.  
> **username_5**: There is a [Strongly-Typed Forth called StrongForth](https://www.stephan-becher.de/strongforth/).  Between Factor, Kitten, and StrongForth, the statement in your question misleads  --  You say "But is there some level of static typing that stack languages can have?" and the answer is "Yes. Completely." Please fix your misleading question!  
---
## 2 answers
### Answer by username_3 on 2023-05-18. Score: 11 | Accepted answer
I said in the comments that I had some disagreement with the premise of the question, but let's dive into why that is. Fundamentally, I think a fully statically typed stack language is eminently possible, and all the trade-offs in doing that are relevant to other paradigms as well.

We can easily define a (non-trivial) sound static type system for the language in your example. One of the rules will be that the body of a loop must complete with the same stack type as it began. It will reject your program as badly-typed, and you'll need to change it. For other functions, it will simulate their stack effects in the obvious way, pushing and popping representations of types to a stack, and reject the program when the stack doesn't meet the function's requirement.
This is a sound static type system and checker. It will reject some programs that perhaps could have run, but that's what all sound static type checkers do. It will allow plenty of programs through, and maybe enough to be useful.
Perhaps we do want this program to run. We could extend the type system: the loop construct is deemed to produce a union type of all possible results¹, and now this program is accepted!
The next question, though, is what we can do after that if we continue the program. We know that what's on top is either an integer or a string, but not which; we should be able to call a function that accepts both of those (perhaps a print, or a rotation), we should be able to drop or duplicate it, and we should be able to push new values onto the stack on top of it.
We can't do anything that requires specifically an integer or specifically a string as an argument, but that's correct — the program would crash some of the time, and that's exactly what a static type system is there to save us from. The language could provide a construct for inspecting the dynamic type — an is-int returning a boolean perhaps, or a pattern-matching system branching on different types. That would be fine to do, and the type system can accommodate these extensions as well.
Perhaps this isn't the language you want to have, which is fine and reasonable, but it's still a stack-based language and it's fully typed. There's nothing particular to a stack language about the complications we're facing here — the sample program is no different to
x = 399
y = "string"
for i from 1 to io.inputAsInt:
   x, y = y, x

We can't determine what type y is here either! A type system for this language would likely also reject the program, or leave us with a union type, and many of the same solutions apply. Just like the example program, this has clear semantics and could run safely to the end in an untyped model.

Now, there are some cases where stack-based languages really are a little different: where the stack is actually the material element. The obvious case is something like 1 io.inputAsInt range loop drop end-loop: we don't know which items are left afterwards, or whether it went off the stack. This program would also be rejected by the type system sketched above, probably even after the extension. Arguably, that's what you want a type system to do for you.
This though is exactly the same problem as running off the end of an array in a procedural language, and it also admits of similar fixes: stack types that incorporate the stack size, rejecting programs that don't validate the change they're going to make, bounded stacks, and so on. All of these tools are available to the language designer, and it's up to them which programs they want to eliminate and where they want to spend their complexity budget to ameliorate it. They also have plenty of options for filling in that lost expression space, like adding more compound types or reified stacks.
Most statically-typed concatenative languages do reject programs like that, at least by default, in favour of having explicit bounds on the stack transformation that a function can do. We can include in that category things like Java bytecode, which is typed and verified before it runs, as well as human-directed programming languages like Kitten.
It's fine for a language to decide it wants an unsound type system instead that lets some of these cases through, and there are plenty of deliberately unsound languages in other paradigms too. The unsound system can still perform useful validations and be worthwhile.
For a short formal treatment of typing concatenative languages you can look at Robert Kleffner's thesis, which also points at earlier work on stack effects in Forth in particular.

¹ This is actually somewhat complicated to do precisely, since there is a dependency between the two types at the top (if one is a string, the other isn't), but it is resolvable, or we can just say the top two entries are typed int|string. It doesn't matter for the moment and so I'm going to ignore that.
---
### Answer by username_6 on 2023-05-18. Score: 9
I'll complement Michael's excellent answer with some examples from an existing stack-based compiled language Factor.
Factor has one primary type system: stack effects. A stack effect of a function describes how many items it consumes and/or produces on the stack. Every defined function in Factor is annotated with its stack effect, which is checked during compilation.
A typical function looks like this:
: add ( x y -- z )
   ;

This add function takes two items on the stack, and produces one.
As a more involved example, the following function loop takes a "quotation" (a statically checked lambda) and repeatedly runs the quotation until it produces an f (false value) on the top. Here, ... means that the function can consume any number of stack items in addition to the parameter pred, but the stack height of ... part must be preserved. In addition, the quotation parameter pred is also checked for its own stack effect at the call site.
: loop ( ... pred: ( ... -- ... ? ) -- ... )
   ;

One could add static typing on the stack items themselves on top of stack effect checking. Factor already has a rudimentary tool for basic typing of this kind, but it can be extended much further.
For example, the swap function (a primitive that swaps two top items) could be typed with two generic type parameters, like ( 't1 't2 -- 't2 't1 ).
For the loop above, one could impose an extra constraint on the ... part: if it consumes n items of type t1, t2, ..., tn respectively, it must output n items of the same types as well. This is analogous to "variadic generics" where the number of generic parameters itself can be generic over integers.
Without automatic union types (as Michael suggested), OP's program won't typecheck because 't1 't2 will be inferred to be int string and [int string] != [string int], which violates the expected ( ... -- ... ) type of loop body.
Other than stack effects and stack element type matching, there is nothing much different from non-stack languages in terms of typing, so you can employ pretty much any type system that works for you. This is also mentioned in Michael's answer, but to reiterate, ultimately there's no difference between trying to type
123 "abc" [ swap ] read-int times

in Factor and
a = 123
b = "abc"
n = int(input())
for _ in range(n):
    a, b = b, a

in Python.
---
