<p>It has been advertised that in type-safe languages, well-typed programs never go wrong, but this doesn't like a legit statement to me:</p>
<ol>
<li>Array indexing is usually by int, but we can freely send out of bound indices or even negative ones. In these cases we get exceptions if we're lucky or crash</li>
<li>Pointer arithmetic is purely chaotic in terms of &quot;going wrong&quot; yet they are type-safe if we disallow casting</li>
<li>Some program that wouldn't go wrong are not well-typed, like <code>&lt;&quot;this is a string&quot;, (λx. &quot;1&quot; + 2)&gt;.1</code> is not well-typed but the code in the second component of the tuple is unreachable hence no type error will occur at runtime</li>
</ol>
<p>It is true that well-typed terms in STLC don't go wrong, but that's because STLC is total and normalizes and wow. Apparently, not all languages are STLC. What am I missing here? Is it actually meaningful to be type-safe?</p>

<lambda-calculus><type-safety>
What's the point of type safety?
CC BY-SA 4.0
2024-02-19T17:30:23.633Z
*"well-typed programs never go wrong"* - do you mean never go wrong due to type-casting errors? It's ludicrous to suggest poor type discipline is the only way programs go wrong.
Steve
CC BY-SA 4.0
2024-02-19T18:14:34.557Z
"Not go wrong" is something which is intentionally somewhat ambiguous without further context. You define what it means to "not go wrong" when you make the language spec. Are you familiar with the [two theorems that make up syntactic type soundness](https://langdev.stackexchange.com/questions/3372/what-does-it-mean-for-a-type-system-or-language-to-be-sound/3377#3377)? Also, have you seen the recent work on semantic type soundness (some of which is linked at the end of the post I've linked)?
David Young
CC BY-SA 4.0
2024-02-19T18:42:36.150Z
This question shows some lack of research. Reading the wikipedia page on type safety as a minimum and then clarifying the question is a good idea here.
Eric Lippert
CC BY-SA 4.0
2024-02-19T19:23:32.610Z
1. Stronger type systems disallow this. This is much the draw of refinement and dependent types. 2. Pointer arithmetic varies by language and is widely considered "unsafe" to begin with: though this usually isn't unsafe in a *type-safe* sense, it can be, depending on the language. 3. Sound types systems allow for false positives to be rejected by the type system, yes. Complete types systems prevent false positives, but completeness is generally not useful and overly restrictive.
apropos
CC BY-SA 4.0
2024-02-20T03:27:45.903Z
@user16217248: I did not vote to close this question. Regardless though, after being on Stack Exchange for 15 years I believe I am a good judge of how and when to vote to close a question.
Eric Lippert
<blockquote>
<p>well-typed programs never go wrong</p>
</blockquote>
<p>“Go wrong” is an informal expression and you need to understand what it means in this context. It doesn't mean that programs written in type-safe languages don't have bugs. No type system is going to flag this code (in a fictional language) as wrong:</p>
<pre><code>let add_one (x : int) = (x + 2) : {y:int | y = x + 2}
</code></pre>
<p>The specification contradicts the function name, but that's beyond the power of a type system, even one that can specify that the return value of the function has an arithmetic relationship with the argument.</p>
<p>A more precise statement would be that <strong>well-typed programs have well-defined behavior</strong>. Or, in other words, the semantics of well-typed languages does not include cases of <a href="https://en.wikipedia.org/wiki/Undefined_behavior" rel="nofollow noreferrer">undefined behavior</a>.</p>
<p>The defined behavior can be to signal an error at runtime. The point of type safety is that you're guaranteed an error, as opposed to really bad effects such as arbitrarily corrupting memory. At one extreme, with a purely dynamic type system such as Lisp or Python, any program might suddenly stop with a runtime type error at any point. Languages with a static type system restrict the places where a runtime error can occur. The more expressive the type system is, the fewer places a runtime error can occur. Due to <a href="https://en.wikipedia.org/wiki/Rice%27s_theorem" rel="nofollow noreferrer">Rice's theorem</a>, you can't have a nontrivial type system that both allows all computable functions and has no runtime errors.</p>
<blockquote>
<p>Array indexing is usually by int, but we can freely send out of bound indices or even negative ones. In these cases we get exceptions if we're lucky or crash</p>
</blockquote>
<p>You don't only get exceptions “if you're lucky”: getting an exception from an out-of-bounds array index is guaranteed. It's part of the semantics of the array indexing operator: <code>a[i]</code> returns the element at position <code>i</code>, or raises the <code>IndexOutOfBounds</code> exception of <code>i</code> is not a valid position. This is different from unsafe languages such as C¹ which cannot guarantee that <code>a</code> is an array and, even if it is, cannot keep track of its size.</p>
<blockquote>
<p>Pointer arithmetic is purely chaotic in terms of &quot;going wrong&quot; yet they are type-safe if we disallow casting</p>
</blockquote>
<p>Pointer arithmetic is array indexing seen from another angle. There are many language features other than casting that can break pointer arithmetic. For example, in C, <code>void *</code> conversion allows the programmer to lie freely about the type of a pointer.</p>
<p>Type-safe languages generally don't allow the programmer to build a pointer. You only have access to objects defined by the language.</p>
<blockquote>
<p>Some program that wouldn't go wrong are not well-typed</p>
</blockquote>
<p>That's true, but irrelevant. The claim is about well-typed programs. It doesn't say anything about programs that are not well-typed.</p>
<blockquote>
<p>It is true that well-typed terms in STLC don't go wrong, but that's because STLC is total</p>
</blockquote>
<p>Yes, “total” is one way to phrase progress.</p>
<blockquote>
<p>and normalizes</p>
</blockquote>
<p>No, normalization is irrelevant. STLC plus a recursion combinator is still type-safe.</p>
<blockquote>
<p>and wow</p>
</blockquote>
<p>I have no idea what this is supposed to mean.</p>
<p>¹ <sub> C as specified in theory or C as implemented in practice. It's theoretically possible to make a C implementation that detects all runtime errors, but it would be extremely inefficient. </sub></p>

CC BY-SA 4.0
2024-02-19T20:40:45.330Z
2024-02-19T20:40:45.330Z
Gilles 'SO- stop being evil'
<p>The wikipedia article on type safety expands upon your &quot;don't go wrong&quot; characterization:</p>
<blockquote>
<p>Intuitively, type soundness is captured by Robin Milner's pithy statement that well-typed programs cannot &quot;go wrong&quot;. In other words, if a type system is sound, then expressions accepted by that type system must evaluate to a value of the appropriate type (rather than produce a value of some other, unrelated type or crash <strong>with a type error</strong>).</p>
</blockquote>
<p>My emphasis on &quot;with a type error&quot;.</p>
<p>This is not the statement that a well-typed program never crashes, and certainly is not the much stronger statement that a well-typed program always terminates with a correct output.</p>
<p>With that in mind we can evaluate type safety in the context of your examples.</p>
<p>In the first example, in a type-safe language the guarantee provided is not &quot;indexing always succeeds&quot;. It is that when doing <code>x[i]</code> when <code>x</code> is <code>T</code>, <strong>if</strong> <code>i</code> is in bounds, <strong>then</strong> the result is a variable of type <code>T</code>&quot;.</p>
<p>In the second example, in a type-safe language the guarantee provided is not &quot;dereferencing a pointer never crashes&quot;. It is that when doing<code>*(x+i)</code> on <code>x</code> of type <code>T*</code> <strong>if</strong> the preconditions of correct pointer arithmetic are met -- that is, the resulting pointer is still inside the bounds of the thing <code>x</code> pointed to -- <strong>then</strong> dereferencing the pointer produces a variable of type <code>T</code>.</p>
<p>I don't understand the third example.</p>
<p>Note also that type safety is a matter of degree. Is C# a type-safe language? To a degree! There are many ways in which C# is unsound so in an absolute sense it is not type-safe, but a foundational design principle is that a great many common type errors must be flagged at compile time.</p>
<blockquote>
<p>What's the point of type safety?</p>
</blockquote>
<p>Primarily, to improve both developer productivity and program correctness by identifying a large class of defects at compile time.</p>
<p>A secondary benefit of type safety is that an optimizer which knows that certain type safety conditions are met can often generate more efficient code. And of course the converse is also true: type-unsafe languages might need to slow down.</p>
<p>My favourite example of the latter going wrong can be found in C# and Java. One of the unsoundnesses I mentioned before is type-unsafe array covariance:</p>
<pre><code>Animal[] animals = new Giraffe[10]; // Weird but legal
animals[1] = new Tiger(); // Runtime type error!
</code></pre>
<p>Since the type system is unsound, it does not prevent the unsafe assignment. Thus the generated code must do a runtime check on the second line to <em>verify</em> that a Tiger can go into this <em>particular</em> array of Animals.</p>
<p>The common case -- the array really is <code>Animal[]</code> as it says on the tin -- gets slower as a result of this unsoundness.</p>

CC BY-SA 4.0
2024-02-19T18:26:12.140Z
2024-02-19T21:23:32.470Z
2024-02-19T21:23:32.470Z
Eric Lippert
CC BY-SA 4.0
2024-02-19T18:30:50.030Z
I think you could clarify that the guarantees listed are examples, not the only possibility. It would be *possible* to design a type system such that `x[i]` was guaranteed in-bounds, for instance, if `x` was defined as `vector{length: 100}` and `i`  as `int{min:0, max:99}`. The hard part - but not impossible - part is constraining *other* operations on `i` so that it is proven to be within those limits for all possible flows through the program.
IMSoP
CC BY-SA 4.0
2024-02-19T18:32:49.097Z
@IMSoP: Sure, you're describing "dependent types". The problem with these type systems is that in rejecting more incorrect programs, they also cause the compiler to either reject more correct programs also, or cause the compiler to not terminate.
Eric Lippert
CC BY-SA 4.0
2024-02-19T18:34:36.363Z
I'm not making any comment on whether such a type system would be better or worse, just that the range of errors covered by the umbrella "type error" depends on what attributes are covered by the implementation of "type". A language with distinct "float" and "integer" types can prove things which a language with only one "number" type cannot; but the concept of "type safety" and "soundness" applies equally to both languages.
IMSoP
<p>Type safety is another layer of bug prevention.</p>
<p>A type unsafe language would let you freely and without any diagnostic message and without conversion (think the auto <code>int</code> to <code>float</code> conversion in many languages) reinterpret any value like another type.</p>
<p>This is what you can do in assembly, <em>everything</em> in assembly is a register-sized value and there is no barrier to interpreting the bits of a float like an integer.</p>
<p>But historically we moved away from the raw assembly model very quickly.</p>
<p>Adding types means that the compiler can catch simple errors like forgetting to make a number constant a floating point value. It also allows for shorthands when dealing with pointers to structures instead of manually computing the offset of a field every time you want to access it.</p>
<p>Doing things like automatic bounds checking is another layer that will need to build on top of basic types. How can you check bounds of an array when you don't have an array with a length you can access?</p>

CC BY-SA 4.0
2024-02-20T11:05:08.510Z
2024-02-20T11:05:08.510Z
ratchet freak
# What's the point of type safety?
Posted by: username_0 on 2024-02-19
It has been advertised that in type-safe languages, well-typed programs never go wrong, but this doesn't like a legit statement to me:

1. Array indexing is usually by int, but we can freely send out of bound indices or even negative ones. In these cases we get exceptions if we're lucky or crash
2. Pointer arithmetic is purely chaotic in terms of "going wrong" yet they are type-safe if we disallow casting
3. Some program that wouldn't go wrong are not well-typed, like `<"this is a string", (λx. "1" + 2)>.1` is not well-typed but the code in the second component of the tuple is unreachable hence no type error will occur at runtime

It is true that well-typed terms in STLC don't go wrong, but that's because STLC is total and normalizes and wow. Apparently, not all languages are STLC. What am I missing here? Is it actually meaningful to be type-safe?
**Tags:** lambda-calculus type-safety
> **Comments:**
> **username_1**: *"well-typed programs never go wrong"* - do you mean never go wrong due to type-casting errors? It's ludicrous to suggest poor type discipline is the only way programs go wrong.  
> **username_2**: "Not go wrong" is something which is intentionally somewhat ambiguous without further context. You define what it means to "not go wrong" when you make the language spec. Are you familiar with the [two theorems that make up syntactic type soundness](https://langdev.stackexchange.com/questions/3372/what-does-it-mean-for-a-type-system-or-language-to-be-sound/3377#3377)? Also, have you seen the recent work on semantic type soundness (some of which is linked at the end of the post I've linked)?  
> **username_3**: This question shows some lack of research. Reading the wikipedia page on type safety as a minimum and then clarifying the question is a good idea here.  
> **username_4**: 1. Stronger type systems disallow this. This is much the draw of refinement and dependent types. 2. Pointer arithmetic varies by language and is widely considered "unsafe" to begin with: though this usually isn't unsafe in a *type-safe* sense, it can be, depending on the language. 3. Sound types systems allow for false positives to be rejected by the type system, yes. Complete types systems prevent false positives, but completeness is generally not useful and overly restrictive.  
> **username_3**: @user16217248: I did not vote to close this question. Regardless though, after being on Stack Exchange for 15 years I believe I am a good judge of how and when to vote to close a question.  
---
## 3 answers
### Answer by username_5 on 2024-02-19. Score: 4
well-typed programs never go wrong

“Go wrong” is an informal expression and you need to understand what it means in this context. It doesn't mean that programs written in type-safe languages don't have bugs. No type system is going to flag this code (in a fictional language) as wrong:
let add_one (x : int) = (x + 2) : {y:int | y = x + 2}

The specification contradicts the function name, but that's beyond the power of a type system, even one that can specify that the return value of the function has an arithmetic relationship with the argument.
A more precise statement would be that well-typed programs have well-defined behavior. Or, in other words, the semantics of well-typed languages does not include cases of undefined behavior.
The defined behavior can be to signal an error at runtime. The point of type safety is that you're guaranteed an error, as opposed to really bad effects such as arbitrarily corrupting memory. At one extreme, with a purely dynamic type system such as Lisp or Python, any program might suddenly stop with a runtime type error at any point. Languages with a static type system restrict the places where a runtime error can occur. The more expressive the type system is, the fewer places a runtime error can occur. Due to Rice's theorem, you can't have a nontrivial type system that both allows all computable functions and has no runtime errors.

Array indexing is usually by int, but we can freely send out of bound indices or even negative ones. In these cases we get exceptions if we're lucky or crash

You don't only get exceptions “if you're lucky”: getting an exception from an out-of-bounds array index is guaranteed. It's part of the semantics of the array indexing operator: a[i] returns the element at position i, or raises the IndexOutOfBounds exception of i is not a valid position. This is different from unsafe languages such as C¹ which cannot guarantee that a is an array and, even if it is, cannot keep track of its size.

Pointer arithmetic is purely chaotic in terms of "going wrong" yet they are type-safe if we disallow casting

Pointer arithmetic is array indexing seen from another angle. There are many language features other than casting that can break pointer arithmetic. For example, in C, void * conversion allows the programmer to lie freely about the type of a pointer.
Type-safe languages generally don't allow the programmer to build a pointer. You only have access to objects defined by the language.

Some program that wouldn't go wrong are not well-typed

That's true, but irrelevant. The claim is about well-typed programs. It doesn't say anything about programs that are not well-typed.

It is true that well-typed terms in STLC don't go wrong, but that's because STLC is total

Yes, “total” is one way to phrase progress.

and normalizes

No, normalization is irrelevant. STLC plus a recursion combinator is still type-safe.

and wow

I have no idea what this is supposed to mean.
¹  C as specified in theory or C as implemented in practice. It's theoretically possible to make a C implementation that detects all runtime errors, but it would be extremely inefficient.
---
### Answer by username_3 on 2024-02-19. Score: 2
The wikipedia article on type safety expands upon your "don't go wrong" characterization:

Intuitively, type soundness is captured by Robin Milner's pithy statement that well-typed programs cannot "go wrong". In other words, if a type system is sound, then expressions accepted by that type system must evaluate to a value of the appropriate type (rather than produce a value of some other, unrelated type or crash with a type error).

My emphasis on "with a type error".
This is not the statement that a well-typed program never crashes, and certainly is not the much stronger statement that a well-typed program always terminates with a correct output.
With that in mind we can evaluate type safety in the context of your examples.
In the first example, in a type-safe language the guarantee provided is not "indexing always succeeds". It is that when doing x[i] when x is T, if i is in bounds, then the result is a variable of type T".
In the second example, in a type-safe language the guarantee provided is not "dereferencing a pointer never crashes". It is that when doing*(x+i) on x of type T* if the preconditions of correct pointer arithmetic are met -- that is, the resulting pointer is still inside the bounds of the thing x pointed to -- then dereferencing the pointer produces a variable of type T.
I don't understand the third example.
Note also that type safety is a matter of degree. Is C# a type-safe language? To a degree! There are many ways in which C# is unsound so in an absolute sense it is not type-safe, but a foundational design principle is that a great many common type errors must be flagged at compile time.

What's the point of type safety?

Primarily, to improve both developer productivity and program correctness by identifying a large class of defects at compile time.
A secondary benefit of type safety is that an optimizer which knows that certain type safety conditions are met can often generate more efficient code. And of course the converse is also true: type-unsafe languages might need to slow down.
My favourite example of the latter going wrong can be found in C# and Java. One of the unsoundnesses I mentioned before is type-unsafe array covariance:
Animal[] animals = new Giraffe[10]; // Weird but legal
animals[1] = new Tiger(); // Runtime type error!

Since the type system is unsound, it does not prevent the unsafe assignment. Thus the generated code must do a runtime check on the second line to verify that a Tiger can go into this particular array of Animals.
The common case -- the array really is Animal[] as it says on the tin -- gets slower as a result of this unsoundness.
> **Comments:**
> **username_6** (2024-02-19): I think you could clarify that the guarantees listed are examples, not the only possibility. It would be *possible* to design a type system such that `x[i]` was guaranteed in-bounds, for instance, if `x` was defined as `vector{length: 100}` and `i`  as `int{min:0, max:99}`. The hard part - but not impossible - part is constraining *other* operations on `i` so that it is proven to be within those limits for all possible flows through the program.  
> **username_3** (2024-02-19): @IMSoP: Sure, you're describing "dependent types". The problem with these type systems is that in rejecting more incorrect programs, they also cause the compiler to either reject more correct programs also, or cause the compiler to not terminate.  
> **username_6** (2024-02-19): I'm not making any comment on whether such a type system would be better or worse, just that the range of errors covered by the umbrella "type error" depends on what attributes are covered by the implementation of "type". A language with distinct "float" and "integer" types can prove things which a language with only one "number" type cannot; but the concept of "type safety" and "soundness" applies equally to both languages.  
---
### Answer by username_7 on 2024-02-20. Score: 1
Type safety is another layer of bug prevention.

A type unsafe language would let you freely and without any diagnostic message and without conversion (think the auto `int` to `float` conversion in many languages) reinterpret any value like another type.

This is what you can do in assembly, *everything* in assembly is a register-sized value and there is no barrier to interpreting the bits of a float like an integer.

But historically we moved away from the raw assembly model very quickly.

Adding types means that the compiler can catch simple errors like forgetting to make a number constant a floating point value. It also allows for shorthands when dealing with pointers to structures instead of manually computing the offset of a field every time you want to access it.

Doing things like automatic bounds checking is another layer that will need to build on top of basic types. How can you check bounds of an array when you don't have an array with a length you can access?
---
